blob: 3cb7c2008cc4b67437c71f32beeb4fc17570027d [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 */
Steve Anton10542f22019-01-11 09:11:00 -080010#include "rtc_base/physical_socket_server.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000011
12#if defined(_MSC_VER) && _MSC_VER < 1300
Yves Gerey665174f2018-06-19 15:03:05 +020013#pragma warning(disable : 4786)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000014#endif
15
pbos@webrtc.org27e58982014-10-07 17:56:53 +000016#ifdef MEMORY_SANITIZER
17#include <sanitizer/msan_interface.h>
18#endif
19
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000020#if defined(WEBRTC_POSIX)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000021#include <fcntl.h>
Yves Gerey665174f2018-06-19 15:03:05 +020022#include <string.h>
jbauchde4db112017-05-31 13:09:18 -070023#if defined(WEBRTC_USE_EPOLL)
24// "poll" will be used to wait for the signal dispatcher.
25#include <poll.h>
26#endif
Yves Gerey665174f2018-06-19 15:03:05 +020027#include <sys/ioctl.h>
28#include <sys/select.h>
29#include <sys/time.h>
30#include <unistd.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000031#endif
32
33#if defined(WEBRTC_WIN)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000034#include <windows.h>
35#include <winsock2.h>
36#include <ws2tcpip.h>
37#undef SetPort
38#endif
39
Patrik Höglunda8005cf2017-12-13 16:05:42 +010040#include <errno.h>
41
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000042#include <algorithm>
43#include <map>
44
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020045#include "rtc_base/arraysize.h"
Steve Anton10542f22019-01-11 09:11:00 -080046#include "rtc_base/byte_order.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "rtc_base/checks.h"
48#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080049#include "rtc_base/network_monitor.h"
50#include "rtc_base/null_socket_server.h"
51#include "rtc_base/time_utils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000052
Emilio Cobos Álvarez68065502019-05-29 15:30:32 +020053#if defined(WEBRTC_LINUX)
54#include <linux/sockios.h>
55#endif
56
Patrik Höglunda8005cf2017-12-13 16:05:42 +010057#if defined(WEBRTC_WIN)
58#define LAST_SYSTEM_ERROR (::GetLastError())
59#elif defined(__native_client__) && __native_client__
60#define LAST_SYSTEM_ERROR (0)
61#elif defined(WEBRTC_POSIX)
62#define LAST_SYSTEM_ERROR (errno)
63#endif // WEBRTC_WIN
64
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000065#if defined(WEBRTC_POSIX)
66#include <netinet/tcp.h> // for TCP_NODELAY
Yves Gerey665174f2018-06-19 15:03:05 +020067#define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000068typedef void* SockOptArg;
Stefan Holmer9131efd2016-05-23 18:19:26 +020069
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000070#endif // WEBRTC_POSIX
71
Stefan Holmer3ebb3ef2016-05-23 20:26:11 +020072#if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) && !defined(__native_client__)
73
Stefan Holmer9131efd2016-05-23 18:19:26 +020074int64_t GetSocketRecvTimestamp(int socket) {
75 struct timeval tv_ioctl;
76 int ret = ioctl(socket, SIOCGSTAMP, &tv_ioctl);
77 if (ret != 0)
78 return -1;
79 int64_t timestamp =
80 rtc::kNumMicrosecsPerSec * static_cast<int64_t>(tv_ioctl.tv_sec) +
81 static_cast<int64_t>(tv_ioctl.tv_usec);
82 return timestamp;
83}
84
85#else
86
87int64_t GetSocketRecvTimestamp(int socket) {
88 return -1;
89}
90#endif
91
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000092#if defined(WEBRTC_WIN)
93typedef char* SockOptArg;
94#endif
95
jbauchde4db112017-05-31 13:09:18 -070096#if defined(WEBRTC_USE_EPOLL)
97// POLLRDHUP / EPOLLRDHUP are only defined starting with Linux 2.6.17.
98#if !defined(POLLRDHUP)
99#define POLLRDHUP 0x2000
100#endif
101#if !defined(EPOLLRDHUP)
102#define EPOLLRDHUP 0x2000
103#endif
104#endif
105
Taylor Brandstetter7b69a442020-08-20 23:43:13 +0000106namespace {
107class ScopedSetTrue {
108 public:
109 ScopedSetTrue(bool* value) : value_(value) {
110 RTC_DCHECK(!*value_);
111 *value_ = true;
112 }
113 ~ScopedSetTrue() { *value_ = false; }
114
115 private:
116 bool* value_;
117};
118} // namespace
119
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000120namespace rtc {
121
danilchapbebf54c2016-04-28 01:32:48 -0700122std::unique_ptr<SocketServer> SocketServer::CreateDefault() {
123#if defined(__native_client__)
124 return std::unique_ptr<SocketServer>(new rtc::NullSocketServer);
125#else
126 return std::unique_ptr<SocketServer>(new rtc::PhysicalSocketServer);
127#endif
128}
129
jbauch095ae152015-12-18 01:39:55 -0800130PhysicalSocket::PhysicalSocket(PhysicalSocketServer* ss, SOCKET s)
Yves Gerey665174f2018-06-19 15:03:05 +0200131 : ss_(ss),
132 s_(s),
133 error_(0),
134 state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED),
135 resolver_(nullptr) {
jbauch095ae152015-12-18 01:39:55 -0800136 if (s_ != INVALID_SOCKET) {
jbauch577f5dc2017-05-17 16:32:26 -0700137 SetEnabledEvents(DE_READ | DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000138
jbauch095ae152015-12-18 01:39:55 -0800139 int type = SOCK_STREAM;
140 socklen_t len = sizeof(type);
nissec16fa5e2017-02-07 07:18:43 -0800141 const int res =
142 getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len);
143 RTC_DCHECK_EQ(0, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000144 udp_ = (SOCK_DGRAM == type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000145 }
jbauch095ae152015-12-18 01:39:55 -0800146}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000147
jbauch095ae152015-12-18 01:39:55 -0800148PhysicalSocket::~PhysicalSocket() {
149 Close();
150}
151
152bool PhysicalSocket::Create(int family, int type) {
153 Close();
154 s_ = ::socket(family, type, 0);
155 udp_ = (SOCK_DGRAM == type);
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800156 family_ = family;
jbauch095ae152015-12-18 01:39:55 -0800157 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700158 if (udp_) {
159 SetEnabledEvents(DE_READ | DE_WRITE);
160 }
jbauch095ae152015-12-18 01:39:55 -0800161 return s_ != INVALID_SOCKET;
162}
163
164SocketAddress PhysicalSocket::GetLocalAddress() const {
Mirko Bonadei108a2f02019-11-20 19:43:38 +0100165 sockaddr_storage addr_storage = {};
jbauch095ae152015-12-18 01:39:55 -0800166 socklen_t addrlen = sizeof(addr_storage);
167 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
168 int result = ::getsockname(s_, addr, &addrlen);
169 SocketAddress address;
170 if (result >= 0) {
171 SocketAddressFromSockAddrStorage(addr_storage, &address);
172 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100173 RTC_LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
174 << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000175 }
jbauch095ae152015-12-18 01:39:55 -0800176 return address;
177}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000178
jbauch095ae152015-12-18 01:39:55 -0800179SocketAddress PhysicalSocket::GetRemoteAddress() const {
Mirko Bonadei108a2f02019-11-20 19:43:38 +0100180 sockaddr_storage addr_storage = {};
jbauch095ae152015-12-18 01:39:55 -0800181 socklen_t addrlen = sizeof(addr_storage);
182 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
183 int result = ::getpeername(s_, addr, &addrlen);
184 SocketAddress address;
185 if (result >= 0) {
186 SocketAddressFromSockAddrStorage(addr_storage, &address);
187 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100188 RTC_LOG(LS_WARNING)
189 << "GetRemoteAddress: unable to get remote addr, socket=" << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000190 }
jbauch095ae152015-12-18 01:39:55 -0800191 return address;
192}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000193
jbauch095ae152015-12-18 01:39:55 -0800194int PhysicalSocket::Bind(const SocketAddress& bind_addr) {
deadbeefc874d122017-02-13 15:41:59 -0800195 SocketAddress copied_bind_addr = bind_addr;
196 // If a network binder is available, use it to bind a socket to an interface
197 // instead of bind(), since this is more reliable on an OS with a weak host
198 // model.
deadbeef9ffa13f2017-02-21 16:18:00 -0800199 if (ss_->network_binder() && !bind_addr.IsAnyIP()) {
deadbeefc874d122017-02-13 15:41:59 -0800200 NetworkBindingResult result =
201 ss_->network_binder()->BindSocketToNetwork(s_, bind_addr.ipaddr());
202 if (result == NetworkBindingResult::SUCCESS) {
203 // Since the network binder handled binding the socket to the desired
204 // network interface, we don't need to (and shouldn't) include an IP in
205 // the bind() call; bind() just needs to assign a port.
206 copied_bind_addr.SetIP(GetAnyIP(copied_bind_addr.ipaddr().family()));
207 } else if (result == NetworkBindingResult::NOT_IMPLEMENTED) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100208 RTC_LOG(LS_INFO) << "Can't bind socket to network because "
209 "network binding is not implemented for this OS.";
deadbeefc874d122017-02-13 15:41:59 -0800210 } else {
211 if (bind_addr.IsLoopbackIP()) {
212 // If we couldn't bind to a loopback IP (which should only happen in
213 // test scenarios), continue on. This may be expected behavior.
Paulina Hensmanb239a2e2020-03-31 16:16:11 +0200214 RTC_LOG(LS_VERBOSE) << "Binding socket to loopback address"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100215 << " failed; result: " << static_cast<int>(result);
deadbeefc874d122017-02-13 15:41:59 -0800216 } else {
Paulina Hensmanb239a2e2020-03-31 16:16:11 +0200217 RTC_LOG(LS_WARNING) << "Binding socket to network address"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100218 << " failed; result: " << static_cast<int>(result);
deadbeefc874d122017-02-13 15:41:59 -0800219 // If a network binding was attempted and failed, we should stop here
220 // and not try to use the socket. Otherwise, we may end up sending
221 // packets with an invalid source address.
222 // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=7026
223 return -1;
224 }
225 }
226 }
jbauch095ae152015-12-18 01:39:55 -0800227 sockaddr_storage addr_storage;
deadbeefc874d122017-02-13 15:41:59 -0800228 size_t len = copied_bind_addr.ToSockAddrStorage(&addr_storage);
jbauch095ae152015-12-18 01:39:55 -0800229 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
230 int err = ::bind(s_, addr, static_cast<int>(len));
231 UpdateLastError();
tfarinaa41ab932015-10-30 16:08:48 -0700232#if !defined(NDEBUG)
jbauch095ae152015-12-18 01:39:55 -0800233 if (0 == err) {
234 dbg_addr_ = "Bound @ ";
235 dbg_addr_.append(GetLocalAddress().ToString());
236 }
tfarinaa41ab932015-10-30 16:08:48 -0700237#endif
jbauch095ae152015-12-18 01:39:55 -0800238 return err;
239}
240
241int PhysicalSocket::Connect(const SocketAddress& addr) {
242 // TODO(pthatcher): Implicit creation is required to reconnect...
243 // ...but should we make it more explicit?
244 if (state_ != CS_CLOSED) {
245 SetError(EALREADY);
246 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000247 }
jbauch095ae152015-12-18 01:39:55 -0800248 if (addr.IsUnresolvedIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100249 RTC_LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
jbauch095ae152015-12-18 01:39:55 -0800250 resolver_ = new AsyncResolver();
251 resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult);
252 resolver_->Start(addr);
253 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254 return 0;
255 }
256
jbauch095ae152015-12-18 01:39:55 -0800257 return DoConnect(addr);
258}
259
260int PhysicalSocket::DoConnect(const SocketAddress& connect_addr) {
Yves Gerey665174f2018-06-19 15:03:05 +0200261 if ((s_ == INVALID_SOCKET) && !Create(connect_addr.family(), SOCK_STREAM)) {
jbauch095ae152015-12-18 01:39:55 -0800262 return SOCKET_ERROR;
263 }
264 sockaddr_storage addr_storage;
265 size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
266 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
267 int err = ::connect(s_, addr, static_cast<int>(len));
268 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700269 uint8_t events = DE_READ | DE_WRITE;
jbauch095ae152015-12-18 01:39:55 -0800270 if (err == 0) {
271 state_ = CS_CONNECTED;
272 } else if (IsBlockingError(GetError())) {
273 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700274 events |= DE_CONNECT;
jbauch095ae152015-12-18 01:39:55 -0800275 } else {
276 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000277 }
278
jbauch577f5dc2017-05-17 16:32:26 -0700279 EnableEvents(events);
jbauch095ae152015-12-18 01:39:55 -0800280 return 0;
281}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000282
jbauch095ae152015-12-18 01:39:55 -0800283int PhysicalSocket::GetError() const {
284 CritScope cs(&crit_);
285 return error_;
286}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000287
jbauch095ae152015-12-18 01:39:55 -0800288void PhysicalSocket::SetError(int error) {
289 CritScope cs(&crit_);
290 error_ = error;
291}
292
293AsyncSocket::ConnState PhysicalSocket::GetState() const {
294 return state_;
295}
296
297int PhysicalSocket::GetOption(Option opt, int* value) {
298 int slevel;
299 int sopt;
300 if (TranslateOption(opt, &slevel, &sopt) == -1)
301 return -1;
302 socklen_t optlen = sizeof(*value);
303 int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800304 if (ret == -1) {
305 return -1;
306 }
307 if (opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000308#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800309 *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000310#endif
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800311 } else if (opt == OPT_DSCP) {
312#if defined(WEBRTC_POSIX)
313 // unshift DSCP value to get six most significant bits of IP DiffServ field
314 *value >>= 2;
315#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000316 }
jbauch095ae152015-12-18 01:39:55 -0800317 return ret;
318}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000319
jbauch095ae152015-12-18 01:39:55 -0800320int PhysicalSocket::SetOption(Option opt, int value) {
321 int slevel;
322 int sopt;
323 if (TranslateOption(opt, &slevel, &sopt) == -1)
324 return -1;
325 if (opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000326#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800327 value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000328#endif
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800329 } else if (opt == OPT_DSCP) {
330#if defined(WEBRTC_POSIX)
331 // shift DSCP value to fit six most significant bits of IP DiffServ field
332 value <<= 2;
333#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000334 }
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800335#if defined(WEBRTC_POSIX)
336 if (sopt == IPV6_TCLASS) {
337 // Set the IPv4 option in all cases to support dual-stack sockets.
Taylor Brandstetter9d269402020-11-25 15:24:53 -0800338 // Don't bother checking the return code, as this is expected to fail if
339 // it's not actually dual-stack.
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800340 ::setsockopt(s_, IPPROTO_IP, IP_TOS, (SockOptArg)&value, sizeof(value));
341 }
342#endif
Taylor Brandstetter9d269402020-11-25 15:24:53 -0800343 int result =
344 ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
345 if (result != 0) {
346 UpdateLastError();
347 }
348 return result;
jbauch095ae152015-12-18 01:39:55 -0800349}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000350
jbauch095ae152015-12-18 01:39:55 -0800351int PhysicalSocket::Send(const void* pv, size_t cb) {
Yves Gerey665174f2018-06-19 15:03:05 +0200352 int sent = DoSend(
353 s_, reinterpret_cast<const char*>(pv), static_cast<int>(cb),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000354#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800355 // Suppress SIGPIPE. Without this, attempting to send on a socket whose
356 // other end is closed will result in a SIGPIPE signal being raised to
357 // our process, which by default will terminate the process, which we
358 // don't want. By specifying this flag, we'll just get the error EPIPE
359 // instead and can handle the error gracefully.
360 MSG_NOSIGNAL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000361#else
jbauch095ae152015-12-18 01:39:55 -0800362 0
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000363#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200364 );
jbauch095ae152015-12-18 01:39:55 -0800365 UpdateLastError();
366 MaybeRemapSendError();
367 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800368 RTC_DCHECK(sent <= static_cast<int>(cb));
jbauchf2a2bf42016-02-03 16:45:32 -0800369 if ((sent > 0 && sent < static_cast<int>(cb)) ||
370 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700371 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000372 }
jbauch095ae152015-12-18 01:39:55 -0800373 return sent;
374}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000375
jbauch095ae152015-12-18 01:39:55 -0800376int PhysicalSocket::SendTo(const void* buffer,
377 size_t length,
378 const SocketAddress& addr) {
379 sockaddr_storage saddr;
380 size_t len = addr.ToSockAddrStorage(&saddr);
Yves Gerey665174f2018-06-19 15:03:05 +0200381 int sent =
382 DoSendTo(s_, static_cast<const char*>(buffer), static_cast<int>(length),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000383#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
Yves Gerey665174f2018-06-19 15:03:05 +0200384 // Suppress SIGPIPE. See above for explanation.
385 MSG_NOSIGNAL,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000386#else
Yves Gerey665174f2018-06-19 15:03:05 +0200387 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000388#endif
Yves Gerey665174f2018-06-19 15:03:05 +0200389 reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
jbauch095ae152015-12-18 01:39:55 -0800390 UpdateLastError();
391 MaybeRemapSendError();
392 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800393 RTC_DCHECK(sent <= static_cast<int>(length));
jbauchf2a2bf42016-02-03 16:45:32 -0800394 if ((sent > 0 && sent < static_cast<int>(length)) ||
395 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700396 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000397 }
jbauch095ae152015-12-18 01:39:55 -0800398 return sent;
399}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000400
Stefan Holmer9131efd2016-05-23 18:19:26 +0200401int PhysicalSocket::Recv(void* buffer, size_t length, int64_t* timestamp) {
Yves Gerey665174f2018-06-19 15:03:05 +0200402 int received =
403 ::recv(s_, static_cast<char*>(buffer), static_cast<int>(length), 0);
jbauch095ae152015-12-18 01:39:55 -0800404 if ((received == 0) && (length != 0)) {
405 // Note: on graceful shutdown, recv can return 0. In this case, we
406 // pretend it is blocking, and then signal close, so that simplifying
407 // assumptions can be made about Recv.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100408 RTC_LOG(LS_WARNING) << "EOF from socket; deferring close event";
jbauch095ae152015-12-18 01:39:55 -0800409 // Must turn this back on so that the select() loop will notice the close
410 // event.
jbauch577f5dc2017-05-17 16:32:26 -0700411 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800412 SetError(EWOULDBLOCK);
413 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000414 }
Stefan Holmer9131efd2016-05-23 18:19:26 +0200415 if (timestamp) {
416 *timestamp = GetSocketRecvTimestamp(s_);
417 }
jbauch095ae152015-12-18 01:39:55 -0800418 UpdateLastError();
419 int error = GetError();
420 bool success = (received >= 0) || IsBlockingError(error);
421 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700422 EnableEvents(DE_READ);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000423 }
jbauch095ae152015-12-18 01:39:55 -0800424 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100425 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000426 }
jbauch095ae152015-12-18 01:39:55 -0800427 return received;
428}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000429
jbauch095ae152015-12-18 01:39:55 -0800430int PhysicalSocket::RecvFrom(void* buffer,
431 size_t length,
Stefan Holmer9131efd2016-05-23 18:19:26 +0200432 SocketAddress* out_addr,
433 int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800434 sockaddr_storage addr_storage;
435 socklen_t addr_len = sizeof(addr_storage);
436 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
437 int received = ::recvfrom(s_, static_cast<char*>(buffer),
438 static_cast<int>(length), 0, addr, &addr_len);
Stefan Holmer9131efd2016-05-23 18:19:26 +0200439 if (timestamp) {
440 *timestamp = GetSocketRecvTimestamp(s_);
441 }
jbauch095ae152015-12-18 01:39:55 -0800442 UpdateLastError();
443 if ((received >= 0) && (out_addr != nullptr))
444 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
445 int error = GetError();
446 bool success = (received >= 0) || IsBlockingError(error);
447 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700448 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800449 }
450 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100451 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
jbauch095ae152015-12-18 01:39:55 -0800452 }
453 return received;
454}
455
456int PhysicalSocket::Listen(int backlog) {
457 int err = ::listen(s_, backlog);
458 UpdateLastError();
459 if (err == 0) {
460 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700461 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800462#if !defined(NDEBUG)
463 dbg_addr_ = "Listening @ ";
464 dbg_addr_.append(GetLocalAddress().ToString());
465#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000466 }
jbauch095ae152015-12-18 01:39:55 -0800467 return err;
468}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000469
jbauch095ae152015-12-18 01:39:55 -0800470AsyncSocket* PhysicalSocket::Accept(SocketAddress* out_addr) {
471 // Always re-subscribe DE_ACCEPT to make sure new incoming connections will
472 // trigger an event even if DoAccept returns an error here.
jbauch577f5dc2017-05-17 16:32:26 -0700473 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800474 sockaddr_storage addr_storage;
475 socklen_t addr_len = sizeof(addr_storage);
476 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
477 SOCKET s = DoAccept(s_, addr, &addr_len);
478 UpdateLastError();
479 if (s == INVALID_SOCKET)
480 return nullptr;
481 if (out_addr != nullptr)
482 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
483 return ss_->WrapSocket(s);
484}
485
486int PhysicalSocket::Close() {
487 if (s_ == INVALID_SOCKET)
488 return 0;
489 int err = ::closesocket(s_);
490 UpdateLastError();
491 s_ = INVALID_SOCKET;
492 state_ = CS_CLOSED;
jbauch577f5dc2017-05-17 16:32:26 -0700493 SetEnabledEvents(0);
jbauch095ae152015-12-18 01:39:55 -0800494 if (resolver_) {
495 resolver_->Destroy(false);
496 resolver_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000497 }
jbauch095ae152015-12-18 01:39:55 -0800498 return err;
499}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000500
jbauch095ae152015-12-18 01:39:55 -0800501SOCKET PhysicalSocket::DoAccept(SOCKET socket,
502 sockaddr* addr,
503 socklen_t* addrlen) {
504 return ::accept(socket, addr, addrlen);
505}
506
jbauchf2a2bf42016-02-03 16:45:32 -0800507int PhysicalSocket::DoSend(SOCKET socket, const char* buf, int len, int flags) {
508 return ::send(socket, buf, len, flags);
509}
510
511int PhysicalSocket::DoSendTo(SOCKET socket,
512 const char* buf,
513 int len,
514 int flags,
515 const struct sockaddr* dest_addr,
516 socklen_t addrlen) {
517 return ::sendto(socket, buf, len, flags, dest_addr, addrlen);
518}
519
jbauch095ae152015-12-18 01:39:55 -0800520void PhysicalSocket::OnResolveResult(AsyncResolverInterface* resolver) {
521 if (resolver != resolver_) {
522 return;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000523 }
524
jbauch095ae152015-12-18 01:39:55 -0800525 int error = resolver_->GetError();
526 if (error == 0) {
527 error = DoConnect(resolver_->address());
528 } else {
529 Close();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000530 }
531
jbauch095ae152015-12-18 01:39:55 -0800532 if (error) {
533 SetError(error);
534 SignalCloseEvent(this, error);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000535 }
jbauch095ae152015-12-18 01:39:55 -0800536}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000537
jbauch095ae152015-12-18 01:39:55 -0800538void PhysicalSocket::UpdateLastError() {
Patrik Höglunda8005cf2017-12-13 16:05:42 +0100539 SetError(LAST_SYSTEM_ERROR);
jbauch095ae152015-12-18 01:39:55 -0800540}
541
542void PhysicalSocket::MaybeRemapSendError() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000543#if defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800544 // https://developer.apple.com/library/mac/documentation/Darwin/
545 // Reference/ManPages/man2/sendto.2.html
546 // ENOBUFS - The output queue for a network interface is full.
547 // This generally indicates that the interface has stopped sending,
548 // but may be caused by transient congestion.
549 if (GetError() == ENOBUFS) {
550 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000551 }
jbauch095ae152015-12-18 01:39:55 -0800552#endif
553}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000554
jbauch577f5dc2017-05-17 16:32:26 -0700555void PhysicalSocket::SetEnabledEvents(uint8_t events) {
556 enabled_events_ = events;
557}
558
559void PhysicalSocket::EnableEvents(uint8_t events) {
560 enabled_events_ |= events;
561}
562
563void PhysicalSocket::DisableEvents(uint8_t events) {
564 enabled_events_ &= ~events;
565}
566
jbauch095ae152015-12-18 01:39:55 -0800567int PhysicalSocket::TranslateOption(Option opt, int* slevel, int* sopt) {
568 switch (opt) {
569 case OPT_DONTFRAGMENT:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000570#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800571 *slevel = IPPROTO_IP;
572 *sopt = IP_DONTFRAGMENT;
573 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000574#elif defined(WEBRTC_MAC) || defined(BSD) || defined(__native_client__)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100575 RTC_LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
jbauch095ae152015-12-18 01:39:55 -0800576 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000577#elif defined(WEBRTC_POSIX)
jbauch095ae152015-12-18 01:39:55 -0800578 *slevel = IPPROTO_IP;
579 *sopt = IP_MTU_DISCOVER;
580 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000581#endif
jbauch095ae152015-12-18 01:39:55 -0800582 case OPT_RCVBUF:
583 *slevel = SOL_SOCKET;
584 *sopt = SO_RCVBUF;
585 break;
586 case OPT_SNDBUF:
587 *slevel = SOL_SOCKET;
588 *sopt = SO_SNDBUF;
589 break;
590 case OPT_NODELAY:
591 *slevel = IPPROTO_TCP;
592 *sopt = TCP_NODELAY;
593 break;
594 case OPT_DSCP:
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800595#if defined(WEBRTC_POSIX)
596 if (family_ == AF_INET6) {
597 *slevel = IPPROTO_IPV6;
598 *sopt = IPV6_TCLASS;
599 } else {
600 *slevel = IPPROTO_IP;
601 *sopt = IP_TOS;
602 }
603 break;
604#else
Mirko Bonadei675513b2017-11-09 11:09:25 +0100605 RTC_LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
jbauch095ae152015-12-18 01:39:55 -0800606 return -1;
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800607#endif
jbauch095ae152015-12-18 01:39:55 -0800608 case OPT_RTP_SENDTIME_EXTN_ID:
609 return -1; // No logging is necessary as this not a OS socket option.
610 default:
nissec80e7412017-01-11 05:56:46 -0800611 RTC_NOTREACHED();
jbauch095ae152015-12-18 01:39:55 -0800612 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000613 }
jbauch095ae152015-12-18 01:39:55 -0800614 return 0;
615}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000616
Yves Gerey665174f2018-06-19 15:03:05 +0200617SocketDispatcher::SocketDispatcher(PhysicalSocketServer* ss)
jbauch4331fcd2016-01-06 22:20:28 -0800618#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200619 : PhysicalSocket(ss),
620 id_(0),
621 signal_close_(false)
jbauch4331fcd2016-01-06 22:20:28 -0800622#else
Yves Gerey665174f2018-06-19 15:03:05 +0200623 : PhysicalSocket(ss)
jbauch4331fcd2016-01-06 22:20:28 -0800624#endif
625{
626}
627
Yves Gerey665174f2018-06-19 15:03:05 +0200628SocketDispatcher::SocketDispatcher(SOCKET s, PhysicalSocketServer* ss)
jbauch4331fcd2016-01-06 22:20:28 -0800629#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200630 : PhysicalSocket(ss, s),
631 id_(0),
632 signal_close_(false)
jbauch4331fcd2016-01-06 22:20:28 -0800633#else
Yves Gerey665174f2018-06-19 15:03:05 +0200634 : PhysicalSocket(ss, s)
jbauch4331fcd2016-01-06 22:20:28 -0800635#endif
636{
637}
638
639SocketDispatcher::~SocketDispatcher() {
640 Close();
641}
642
643bool SocketDispatcher::Initialize() {
nisseede5da42017-01-12 05:15:36 -0800644 RTC_DCHECK(s_ != INVALID_SOCKET);
Yves Gerey665174f2018-06-19 15:03:05 +0200645// Must be a non-blocking
jbauch4331fcd2016-01-06 22:20:28 -0800646#if defined(WEBRTC_WIN)
647 u_long argp = 1;
648 ioctlsocket(s_, FIONBIO, &argp);
649#elif defined(WEBRTC_POSIX)
650 fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
651#endif
deadbeefeae45642017-05-26 16:27:09 -0700652#if defined(WEBRTC_IOS)
653 // iOS may kill sockets when the app is moved to the background
654 // (specifically, if the app doesn't use the "voip" UIBackgroundMode). When
655 // we attempt to write to such a socket, SIGPIPE will be raised, which by
656 // default will terminate the process, which we don't want. By specifying
657 // this socket option, SIGPIPE will be disabled for the socket.
658 int value = 1;
659 ::setsockopt(s_, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value));
660#endif
jbauch4331fcd2016-01-06 22:20:28 -0800661 ss_->Add(this);
662 return true;
663}
664
665bool SocketDispatcher::Create(int type) {
666 return Create(AF_INET, type);
667}
668
669bool SocketDispatcher::Create(int family, int type) {
670 // Change the socket to be non-blocking.
671 if (!PhysicalSocket::Create(family, type))
672 return false;
673
674 if (!Initialize())
675 return false;
676
677#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200678 do {
679 id_ = ++next_id_;
680 } while (id_ == 0);
jbauch4331fcd2016-01-06 22:20:28 -0800681#endif
682 return true;
683}
684
685#if defined(WEBRTC_WIN)
686
687WSAEVENT SocketDispatcher::GetWSAEvent() {
688 return WSA_INVALID_EVENT;
689}
690
691SOCKET SocketDispatcher::GetSocket() {
692 return s_;
693}
694
695bool SocketDispatcher::CheckSignalClose() {
696 if (!signal_close_)
697 return false;
698
699 char ch;
700 if (recv(s_, &ch, 1, MSG_PEEK) > 0)
701 return false;
702
703 state_ = CS_CLOSED;
704 signal_close_ = false;
705 SignalCloseEvent(this, signal_err_);
706 return true;
707}
708
709int SocketDispatcher::next_id_ = 0;
710
711#elif defined(WEBRTC_POSIX)
712
713int SocketDispatcher::GetDescriptor() {
714 return s_;
715}
716
717bool SocketDispatcher::IsDescriptorClosed() {
deadbeeffaedf7f2017-02-09 15:09:22 -0800718 if (udp_) {
719 // The MSG_PEEK trick doesn't work for UDP, since (at least in some
720 // circumstances) it requires reading an entire UDP packet, which would be
721 // bad for performance here. So, just check whether |s_| has been closed,
722 // which should be sufficient.
723 return s_ == INVALID_SOCKET;
724 }
jbauch4331fcd2016-01-06 22:20:28 -0800725 // We don't have a reliable way of distinguishing end-of-stream
726 // from readability. So test on each readable call. Is this
727 // inefficient? Probably.
728 char ch;
729 ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
730 if (res > 0) {
731 // Data available, so not closed.
732 return false;
733 } else if (res == 0) {
734 // EOF, so closed.
735 return true;
736 } else { // error
737 switch (errno) {
738 // Returned if we've already closed s_.
739 case EBADF:
740 // Returned during ungraceful peer shutdown.
741 case ECONNRESET:
742 return true;
deadbeeffaedf7f2017-02-09 15:09:22 -0800743 // The normal blocking error; don't log anything.
744 case EWOULDBLOCK:
745 // Interrupted system call.
746 case EINTR:
747 return false;
jbauch4331fcd2016-01-06 22:20:28 -0800748 default:
749 // Assume that all other errors are just blocking errors, meaning the
750 // connection is still good but we just can't read from it right now.
751 // This should only happen when connecting (and at most once), because
752 // in all other cases this function is only called if the file
753 // descriptor is already known to be in the readable state. However,
754 // it's not necessary a problem if we spuriously interpret a
755 // "connection lost"-type error as a blocking error, because typically
756 // the next recv() will get EOF, so we'll still eventually notice that
757 // the socket is closed.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100758 RTC_LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
jbauch4331fcd2016-01-06 22:20:28 -0800759 return false;
760 }
761 }
762}
763
Yves Gerey665174f2018-06-19 15:03:05 +0200764#endif // WEBRTC_POSIX
jbauch4331fcd2016-01-06 22:20:28 -0800765
766uint32_t SocketDispatcher::GetRequestedEvents() {
jbauch577f5dc2017-05-17 16:32:26 -0700767 return enabled_events();
jbauch4331fcd2016-01-06 22:20:28 -0800768}
769
770void SocketDispatcher::OnPreEvent(uint32_t ff) {
771 if ((ff & DE_CONNECT) != 0)
772 state_ = CS_CONNECTED;
773
774#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200775// We set CS_CLOSED from CheckSignalClose.
jbauch4331fcd2016-01-06 22:20:28 -0800776#elif defined(WEBRTC_POSIX)
777 if ((ff & DE_CLOSE) != 0)
778 state_ = CS_CLOSED;
779#endif
780}
781
782#if defined(WEBRTC_WIN)
783
784void SocketDispatcher::OnEvent(uint32_t ff, int err) {
785 int cache_id = id_;
786 // Make sure we deliver connect/accept first. Otherwise, consumers may see
787 // something like a READ followed by a CONNECT, which would be odd.
788 if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
789 if (ff != DE_CONNECT)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100790 RTC_LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
jbauch577f5dc2017-05-17 16:32:26 -0700791 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800792#if !defined(NDEBUG)
793 dbg_addr_ = "Connected @ ";
794 dbg_addr_.append(GetRemoteAddress().ToString());
795#endif
796 SignalConnectEvent(this);
797 }
798 if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700799 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800800 SignalReadEvent(this);
801 }
802 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700803 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800804 SignalReadEvent(this);
805 }
806 if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700807 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800808 SignalWriteEvent(this);
809 }
810 if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
811 signal_close_ = true;
812 signal_err_ = err;
813 }
814}
815
816#elif defined(WEBRTC_POSIX)
817
818void SocketDispatcher::OnEvent(uint32_t ff, int err) {
jbauchde4db112017-05-31 13:09:18 -0700819#if defined(WEBRTC_USE_EPOLL)
820 // Remember currently enabled events so we can combine multiple changes
821 // into one update call later.
822 // The signal handlers might re-enable events disabled here, so we can't
823 // keep a list of events to disable at the end of the method. This list
824 // would not be updated with the events enabled by the signal handlers.
825 StartBatchedEventUpdates();
826#endif
jbauch4331fcd2016-01-06 22:20:28 -0800827 // Make sure we deliver connect/accept first. Otherwise, consumers may see
828 // something like a READ followed by a CONNECT, which would be odd.
829 if ((ff & DE_CONNECT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700830 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800831 SignalConnectEvent(this);
832 }
833 if ((ff & DE_ACCEPT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700834 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800835 SignalReadEvent(this);
836 }
837 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700838 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800839 SignalReadEvent(this);
840 }
841 if ((ff & DE_WRITE) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700842 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800843 SignalWriteEvent(this);
844 }
845 if ((ff & DE_CLOSE) != 0) {
846 // The socket is now dead to us, so stop checking it.
jbauch577f5dc2017-05-17 16:32:26 -0700847 SetEnabledEvents(0);
jbauch4331fcd2016-01-06 22:20:28 -0800848 SignalCloseEvent(this, err);
849 }
jbauchde4db112017-05-31 13:09:18 -0700850#if defined(WEBRTC_USE_EPOLL)
851 FinishBatchedEventUpdates();
852#endif
jbauch4331fcd2016-01-06 22:20:28 -0800853}
854
Yves Gerey665174f2018-06-19 15:03:05 +0200855#endif // WEBRTC_POSIX
jbauch4331fcd2016-01-06 22:20:28 -0800856
jbauchde4db112017-05-31 13:09:18 -0700857#if defined(WEBRTC_USE_EPOLL)
858
Taylor Brandstetter7b69a442020-08-20 23:43:13 +0000859inline static int GetEpollEvents(uint32_t ff) {
jbauchde4db112017-05-31 13:09:18 -0700860 int events = 0;
861 if (ff & (DE_READ | DE_ACCEPT)) {
862 events |= EPOLLIN;
863 }
864 if (ff & (DE_WRITE | DE_CONNECT)) {
865 events |= EPOLLOUT;
866 }
867 return events;
868}
869
870void SocketDispatcher::StartBatchedEventUpdates() {
871 RTC_DCHECK_EQ(saved_enabled_events_, -1);
872 saved_enabled_events_ = enabled_events();
873}
874
875void SocketDispatcher::FinishBatchedEventUpdates() {
876 RTC_DCHECK_NE(saved_enabled_events_, -1);
877 uint8_t old_events = static_cast<uint8_t>(saved_enabled_events_);
878 saved_enabled_events_ = -1;
879 MaybeUpdateDispatcher(old_events);
880}
881
882void SocketDispatcher::MaybeUpdateDispatcher(uint8_t old_events) {
883 if (GetEpollEvents(enabled_events()) != GetEpollEvents(old_events) &&
884 saved_enabled_events_ == -1) {
885 ss_->Update(this);
886 }
887}
888
889void SocketDispatcher::SetEnabledEvents(uint8_t events) {
890 uint8_t old_events = enabled_events();
891 PhysicalSocket::SetEnabledEvents(events);
892 MaybeUpdateDispatcher(old_events);
893}
894
895void SocketDispatcher::EnableEvents(uint8_t events) {
896 uint8_t old_events = enabled_events();
897 PhysicalSocket::EnableEvents(events);
898 MaybeUpdateDispatcher(old_events);
899}
900
901void SocketDispatcher::DisableEvents(uint8_t events) {
902 uint8_t old_events = enabled_events();
903 PhysicalSocket::DisableEvents(events);
904 MaybeUpdateDispatcher(old_events);
905}
906
907#endif // WEBRTC_USE_EPOLL
908
jbauch4331fcd2016-01-06 22:20:28 -0800909int SocketDispatcher::Close() {
910 if (s_ == INVALID_SOCKET)
911 return 0;
912
913#if defined(WEBRTC_WIN)
914 id_ = 0;
915 signal_close_ = false;
916#endif
mmorrison25eeda12020-04-07 16:13:13 -0600917#if defined(WEBRTC_USE_EPOLL)
918 // If we're batching events, the socket can be closed and reopened
919 // during the batch. Set saved_enabled_events_ to 0 here so the new
920 // socket, if any, has the correct old events bitfield
921 if (saved_enabled_events_ != -1) {
922 saved_enabled_events_ = 0;
923 }
924#endif
jbauch4331fcd2016-01-06 22:20:28 -0800925 ss_->Remove(this);
926 return PhysicalSocket::Close();
927}
928
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000929#if defined(WEBRTC_POSIX)
930class EventDispatcher : public Dispatcher {
931 public:
932 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
933 if (pipe(afd_) < 0)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100934 RTC_LOG(LERROR) << "pipe failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000935 ss_->Add(this);
936 }
937
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000938 ~EventDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000939 ss_->Remove(this);
940 close(afd_[0]);
941 close(afd_[1]);
942 }
943
944 virtual void Signal() {
945 CritScope cs(&crit_);
946 if (!fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200947 const uint8_t b[1] = {0};
nissec16fa5e2017-02-07 07:18:43 -0800948 const ssize_t res = write(afd_[1], b, sizeof(b));
949 RTC_DCHECK_EQ(1, res);
950 fSignaled_ = true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000951 }
952 }
953
Peter Boström0c4e06b2015-10-07 12:23:21 +0200954 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000955
Peter Boström0c4e06b2015-10-07 12:23:21 +0200956 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000957 // It is not possible to perfectly emulate an auto-resetting event with
958 // pipes. This simulates it by resetting before the event is handled.
959
960 CritScope cs(&crit_);
961 if (fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200962 uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
nissec16fa5e2017-02-07 07:18:43 -0800963 const ssize_t res = read(afd_[0], b, sizeof(b));
964 RTC_DCHECK_EQ(1, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000965 fSignaled_ = false;
966 }
967 }
968
nissec80e7412017-01-11 05:56:46 -0800969 void OnEvent(uint32_t ff, int err) override { RTC_NOTREACHED(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000970
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000971 int GetDescriptor() override { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000972
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000973 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000974
975 private:
Yves Gerey665174f2018-06-19 15:03:05 +0200976 PhysicalSocketServer* ss_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000977 int afd_[2];
978 bool fSignaled_;
Markus Handell3cb525b2020-07-16 16:16:09 +0200979 RecursiveCriticalSection crit_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000980};
981
Yves Gerey665174f2018-06-19 15:03:05 +0200982#endif // WEBRTC_POSIX
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000983
984#if defined(WEBRTC_WIN)
Peter Boström0c4e06b2015-10-07 12:23:21 +0200985static uint32_t FlagsToEvents(uint32_t events) {
986 uint32_t ffFD = FD_CLOSE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000987 if (events & DE_READ)
988 ffFD |= FD_READ;
989 if (events & DE_WRITE)
990 ffFD |= FD_WRITE;
991 if (events & DE_CONNECT)
992 ffFD |= FD_CONNECT;
993 if (events & DE_ACCEPT)
994 ffFD |= FD_ACCEPT;
995 return ffFD;
996}
997
998class EventDispatcher : public Dispatcher {
999 public:
Yves Gerey665174f2018-06-19 15:03:05 +02001000 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001001 hev_ = WSACreateEvent();
1002 if (hev_) {
1003 ss_->Add(this);
1004 }
1005 }
1006
Steve Anton9de3aac2017-10-24 10:08:26 -07001007 ~EventDispatcher() override {
deadbeef37f5ecf2017-02-27 14:06:41 -08001008 if (hev_ != nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001009 ss_->Remove(this);
1010 WSACloseEvent(hev_);
deadbeef37f5ecf2017-02-27 14:06:41 -08001011 hev_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001012 }
1013 }
1014
1015 virtual void Signal() {
deadbeef37f5ecf2017-02-27 14:06:41 -08001016 if (hev_ != nullptr)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001017 WSASetEvent(hev_);
1018 }
1019
Steve Anton9de3aac2017-10-24 10:08:26 -07001020 uint32_t GetRequestedEvents() override { return 0; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001021
Steve Anton9de3aac2017-10-24 10:08:26 -07001022 void OnPreEvent(uint32_t ff) override { WSAResetEvent(hev_); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001023
Steve Anton9de3aac2017-10-24 10:08:26 -07001024 void OnEvent(uint32_t ff, int err) override {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001025
Steve Anton9de3aac2017-10-24 10:08:26 -07001026 WSAEVENT GetWSAEvent() override { return hev_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001027
Steve Anton9de3aac2017-10-24 10:08:26 -07001028 SOCKET GetSocket() override { return INVALID_SOCKET; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001029
Steve Anton9de3aac2017-10-24 10:08:26 -07001030 bool CheckSignalClose() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001031
Steve Anton9de3aac2017-10-24 10:08:26 -07001032 private:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001033 PhysicalSocketServer* ss_;
1034 WSAEVENT hev_;
1035};
honghaizcec0a082016-01-15 14:49:09 -08001036#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001037
1038// Sets the value of a boolean value to false when signaled.
1039class Signaler : public EventDispatcher {
1040 public:
Yves Gerey665174f2018-06-19 15:03:05 +02001041 Signaler(PhysicalSocketServer* ss, bool* pf) : EventDispatcher(ss), pf_(pf) {}
1042 ~Signaler() override {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001043
Peter Boström0c4e06b2015-10-07 12:23:21 +02001044 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001045 if (pf_)
1046 *pf_ = false;
1047 }
1048
1049 private:
Yves Gerey665174f2018-06-19 15:03:05 +02001050 bool* pf_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001051};
1052
Niels Möller611fba42020-05-13 14:42:22 +02001053PhysicalSocketServer::PhysicalSocketServer()
1054 :
jbauchde4db112017-05-31 13:09:18 -07001055#if defined(WEBRTC_USE_EPOLL)
Niels Möller611fba42020-05-13 14:42:22 +02001056 // Since Linux 2.6.8, the size argument is ignored, but must be greater
1057 // than zero. Before that the size served as hint to the kernel for the
1058 // amount of space to initially allocate in internal data structures.
1059 epoll_fd_(epoll_create(FD_SETSIZE)),
1060#endif
1061#if defined(WEBRTC_WIN)
1062 socket_ev_(WSACreateEvent()),
1063#endif
1064 fWait_(false) {
1065#if defined(WEBRTC_USE_EPOLL)
jbauchde4db112017-05-31 13:09:18 -07001066 if (epoll_fd_ == -1) {
1067 // Not an error, will fall back to "select" below.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001068 RTC_LOG_E(LS_WARNING, EN, errno) << "epoll_create";
Niels Möller611fba42020-05-13 14:42:22 +02001069 // Note that -1 == INVALID_SOCKET, the alias used by later checks.
jbauchde4db112017-05-31 13:09:18 -07001070 }
1071#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001072 signal_wakeup_ = new Signaler(this, &fWait_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001073}
1074
1075PhysicalSocketServer::~PhysicalSocketServer() {
1076#if defined(WEBRTC_WIN)
1077 WSACloseEvent(socket_ev_);
1078#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001079 delete signal_wakeup_;
jbauchde4db112017-05-31 13:09:18 -07001080#if defined(WEBRTC_USE_EPOLL)
1081 if (epoll_fd_ != INVALID_SOCKET) {
1082 close(epoll_fd_);
1083 }
1084#endif
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001085 RTC_DCHECK(dispatcher_by_key_.empty());
1086 RTC_DCHECK(key_by_dispatcher_.empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001087}
1088
1089void PhysicalSocketServer::WakeUp() {
1090 signal_wakeup_->Signal();
1091}
1092
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001093Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
1094 PhysicalSocket* socket = new PhysicalSocket(this);
1095 if (socket->Create(family, type)) {
1096 return socket;
1097 } else {
1098 delete socket;
jbauch095ae152015-12-18 01:39:55 -08001099 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001100 }
1101}
1102
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001103AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
1104 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1105 if (dispatcher->Create(family, type)) {
1106 return dispatcher;
1107 } else {
1108 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001109 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001110 }
1111}
1112
1113AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
1114 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1115 if (dispatcher->Initialize()) {
1116 return dispatcher;
1117 } else {
1118 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001119 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001120 }
1121}
1122
Yves Gerey665174f2018-06-19 15:03:05 +02001123void PhysicalSocketServer::Add(Dispatcher* pdispatcher) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001124 CritScope cs(&crit_);
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001125 if (key_by_dispatcher_.count(pdispatcher)) {
1126 RTC_LOG(LS_WARNING)
1127 << "PhysicalSocketServer asked to add a duplicate dispatcher.";
1128 return;
jbauchde4db112017-05-31 13:09:18 -07001129 }
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001130 uint64_t key = next_dispatcher_key_++;
1131 dispatcher_by_key_.emplace(key, pdispatcher);
1132 key_by_dispatcher_.emplace(pdispatcher, key);
jbauchde4db112017-05-31 13:09:18 -07001133#if defined(WEBRTC_USE_EPOLL)
1134 if (epoll_fd_ != INVALID_SOCKET) {
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001135 AddEpoll(pdispatcher, key);
jbauchde4db112017-05-31 13:09:18 -07001136 }
1137#endif // WEBRTC_USE_EPOLL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001138}
1139
Yves Gerey665174f2018-06-19 15:03:05 +02001140void PhysicalSocketServer::Remove(Dispatcher* pdispatcher) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001141 CritScope cs(&crit_);
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001142 if (!key_by_dispatcher_.count(pdispatcher)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001143 RTC_LOG(LS_WARNING)
1144 << "PhysicalSocketServer asked to remove a unknown "
Jonas Olssonb2b20312020-01-14 12:11:31 +01001145 "dispatcher, potentially from a duplicate call to Add.";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001146 return;
1147 }
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001148 uint64_t key = key_by_dispatcher_.at(pdispatcher);
1149 key_by_dispatcher_.erase(pdispatcher);
1150 dispatcher_by_key_.erase(key);
jbauchde4db112017-05-31 13:09:18 -07001151#if defined(WEBRTC_USE_EPOLL)
1152 if (epoll_fd_ != INVALID_SOCKET) {
1153 RemoveEpoll(pdispatcher);
1154 }
1155#endif // WEBRTC_USE_EPOLL
1156}
1157
1158void PhysicalSocketServer::Update(Dispatcher* pdispatcher) {
1159#if defined(WEBRTC_USE_EPOLL)
1160 if (epoll_fd_ == INVALID_SOCKET) {
1161 return;
1162 }
1163
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001164 // Don't update dispatchers that haven't yet been added.
jbauchde4db112017-05-31 13:09:18 -07001165 CritScope cs(&crit_);
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001166 if (!key_by_dispatcher_.count(pdispatcher)) {
jbauchde4db112017-05-31 13:09:18 -07001167 return;
1168 }
1169
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001170 UpdateEpoll(pdispatcher, key_by_dispatcher_.at(pdispatcher));
jbauchde4db112017-05-31 13:09:18 -07001171#endif
1172}
1173
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001174#if defined(WEBRTC_POSIX)
jbauchde4db112017-05-31 13:09:18 -07001175
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001176bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001177 // We don't support reentrant waiting.
1178 RTC_DCHECK(!waiting_);
1179 ScopedSetTrue s(&waiting_);
jbauchde4db112017-05-31 13:09:18 -07001180#if defined(WEBRTC_USE_EPOLL)
1181 // We don't keep a dedicated "epoll" descriptor containing only the non-IO
1182 // (i.e. signaling) dispatcher, so "poll" will be used instead of the default
1183 // "select" to support sockets larger than FD_SETSIZE.
1184 if (!process_io) {
1185 return WaitPoll(cmsWait, signal_wakeup_);
1186 } else if (epoll_fd_ != INVALID_SOCKET) {
1187 return WaitEpoll(cmsWait);
1188 }
1189#endif
1190 return WaitSelect(cmsWait, process_io);
1191}
1192
1193static void ProcessEvents(Dispatcher* dispatcher,
1194 bool readable,
1195 bool writable,
1196 bool check_error) {
1197 int errcode = 0;
1198 // TODO(pthatcher): Should we set errcode if getsockopt fails?
1199 if (check_error) {
1200 socklen_t len = sizeof(errcode);
1201 ::getsockopt(dispatcher->GetDescriptor(), SOL_SOCKET, SO_ERROR, &errcode,
1202 &len);
1203 }
1204
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001205 // Most often the socket is writable or readable or both, so make a single
1206 // virtual call to get requested events
1207 const uint32_t requested_events = dispatcher->GetRequestedEvents();
jbauchde4db112017-05-31 13:09:18 -07001208 uint32_t ff = 0;
1209
1210 // Check readable descriptors. If we're waiting on an accept, signal
1211 // that. Otherwise we're waiting for data, check to see if we're
1212 // readable or really closed.
1213 // TODO(pthatcher): Only peek at TCP descriptors.
1214 if (readable) {
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001215 if (requested_events & DE_ACCEPT) {
jbauchde4db112017-05-31 13:09:18 -07001216 ff |= DE_ACCEPT;
1217 } else if (errcode || dispatcher->IsDescriptorClosed()) {
1218 ff |= DE_CLOSE;
1219 } else {
1220 ff |= DE_READ;
1221 }
1222 }
1223
1224 // Check writable descriptors. If we're waiting on a connect, detect
1225 // success versus failure by the reaped error code.
1226 if (writable) {
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001227 if (requested_events & DE_CONNECT) {
jbauchde4db112017-05-31 13:09:18 -07001228 if (!errcode) {
1229 ff |= DE_CONNECT;
1230 } else {
1231 ff |= DE_CLOSE;
1232 }
1233 } else {
1234 ff |= DE_WRITE;
1235 }
1236 }
1237
1238 // Tell the descriptor about the event.
1239 if (ff != 0) {
1240 dispatcher->OnPreEvent(ff);
1241 dispatcher->OnEvent(ff, errcode);
1242 }
1243}
1244
1245bool PhysicalSocketServer::WaitSelect(int cmsWait, bool process_io) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001246 // Calculate timing information
1247
deadbeef37f5ecf2017-02-27 14:06:41 -08001248 struct timeval* ptvWait = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001249 struct timeval tvWait;
Niels Möller689b5872018-08-29 09:55:44 +02001250 int64_t stop_us;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001251 if (cmsWait != kForever) {
1252 // Calculate wait timeval
1253 tvWait.tv_sec = cmsWait / 1000;
1254 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1255 ptvWait = &tvWait;
1256
Niels Möller689b5872018-08-29 09:55:44 +02001257 // Calculate when to return
1258 stop_us = rtc::TimeMicros() + cmsWait * 1000;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001259 }
1260
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001261
1262 fd_set fdsRead;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001263 fd_set fdsWrite;
Yves Gerey665174f2018-06-19 15:03:05 +02001264// Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1265// inline assembly in FD_ZERO.
1266// http://crbug.com/344505
pbos@webrtc.org27e58982014-10-07 17:56:53 +00001267#ifdef MEMORY_SANITIZER
1268 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1269 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1270#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001271
1272 fWait_ = true;
1273
1274 while (fWait_) {
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001275 // Zero all fd_sets. Although select() zeros the descriptors not signaled,
1276 // we may need to do this for dispatchers that were deleted while
1277 // iterating.
1278 FD_ZERO(&fdsRead);
1279 FD_ZERO(&fdsWrite);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001280 int fdmax = -1;
1281 {
1282 CritScope cr(&crit_);
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001283 current_dispatcher_keys_.clear();
1284 for (auto const& kv : dispatcher_by_key_) {
1285 uint64_t key = kv.first;
1286 Dispatcher* pdispatcher = kv.second;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001287 // Query dispatchers for read and write wait state
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001288 if (!process_io && (pdispatcher != signal_wakeup_))
1289 continue;
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001290 current_dispatcher_keys_.push_back(key);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001291 int fd = pdispatcher->GetDescriptor();
jbauchde4db112017-05-31 13:09:18 -07001292 // "select"ing a file descriptor that is equal to or larger than
1293 // FD_SETSIZE will result in undefined behavior.
1294 RTC_DCHECK_LT(fd, FD_SETSIZE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001295 if (fd > fdmax)
1296 fdmax = fd;
1297
Peter Boström0c4e06b2015-10-07 12:23:21 +02001298 uint32_t ff = pdispatcher->GetRequestedEvents();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001299 if (ff & (DE_READ | DE_ACCEPT))
1300 FD_SET(fd, &fdsRead);
1301 if (ff & (DE_WRITE | DE_CONNECT))
1302 FD_SET(fd, &fdsWrite);
1303 }
1304 }
1305
1306 // Wait then call handlers as appropriate
1307 // < 0 means error
1308 // 0 means timeout
1309 // > 0 means count of descriptors ready
deadbeef37f5ecf2017-02-27 14:06:41 -08001310 int n = select(fdmax + 1, &fdsRead, &fdsWrite, nullptr, ptvWait);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001311
1312 // If error, return error.
1313 if (n < 0) {
1314 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001315 RTC_LOG_E(LS_ERROR, EN, errno) << "select";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001316 return false;
1317 }
1318 // Else ignore the error and keep going. If this EINTR was for one of the
1319 // signals managed by this PhysicalSocketServer, the
1320 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1321 // iteration.
1322 } else if (n == 0) {
1323 // If timeout, return success
1324 return true;
1325 } else {
1326 // We have signaled descriptors
1327 CritScope cr(&crit_);
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001328 // Iterate only on the dispatchers whose sockets were passed into
1329 // WSAEventSelect; this avoids the ABA problem (a socket being
1330 // destroyed and a new one created with the same file descriptor).
1331 for (uint64_t key : current_dispatcher_keys_) {
1332 if (!dispatcher_by_key_.count(key))
1333 continue;
1334 Dispatcher* pdispatcher = dispatcher_by_key_.at(key);
1335
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001336 int fd = pdispatcher->GetDescriptor();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001337
jbauchde4db112017-05-31 13:09:18 -07001338 bool readable = FD_ISSET(fd, &fdsRead);
1339 if (readable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001340 FD_CLR(fd, &fdsRead);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001341 }
1342
jbauchde4db112017-05-31 13:09:18 -07001343 bool writable = FD_ISSET(fd, &fdsWrite);
1344 if (writable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001345 FD_CLR(fd, &fdsWrite);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001346 }
1347
jbauchde4db112017-05-31 13:09:18 -07001348 // The error code can be signaled through reads or writes.
1349 ProcessEvents(pdispatcher, readable, writable, readable || writable);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001350 }
1351 }
1352
1353 // Recalc the time remaining to wait. Doing it here means it doesn't get
1354 // calced twice the first time through the loop
1355 if (ptvWait) {
1356 ptvWait->tv_sec = 0;
1357 ptvWait->tv_usec = 0;
Niels Möller689b5872018-08-29 09:55:44 +02001358 int64_t time_left_us = stop_us - rtc::TimeMicros();
1359 if (time_left_us > 0) {
1360 ptvWait->tv_sec = time_left_us / rtc::kNumMicrosecsPerSec;
1361 ptvWait->tv_usec = time_left_us % rtc::kNumMicrosecsPerSec;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001362 }
1363 }
1364 }
1365
1366 return true;
1367}
1368
jbauchde4db112017-05-31 13:09:18 -07001369#if defined(WEBRTC_USE_EPOLL)
1370
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001371void PhysicalSocketServer::AddEpoll(Dispatcher* pdispatcher, uint64_t key) {
jbauchde4db112017-05-31 13:09:18 -07001372 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1373 int fd = pdispatcher->GetDescriptor();
1374 RTC_DCHECK(fd != INVALID_SOCKET);
1375 if (fd == INVALID_SOCKET) {
1376 return;
1377 }
1378
1379 struct epoll_event event = {0};
1380 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001381 event.data.u64 = key;
jbauchde4db112017-05-31 13:09:18 -07001382 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &event);
1383 RTC_DCHECK_EQ(err, 0);
1384 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001385 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_ADD";
jbauchde4db112017-05-31 13:09:18 -07001386 }
1387}
1388
1389void PhysicalSocketServer::RemoveEpoll(Dispatcher* pdispatcher) {
1390 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1391 int fd = pdispatcher->GetDescriptor();
1392 RTC_DCHECK(fd != INVALID_SOCKET);
1393 if (fd == INVALID_SOCKET) {
1394 return;
1395 }
1396
1397 struct epoll_event event = {0};
1398 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &event);
1399 RTC_DCHECK(err == 0 || errno == ENOENT);
1400 if (err == -1) {
1401 if (errno == ENOENT) {
1402 // Socket has already been closed.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001403 RTC_LOG_E(LS_VERBOSE, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001404 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001405 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001406 }
1407 }
1408}
1409
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001410void PhysicalSocketServer::UpdateEpoll(Dispatcher* pdispatcher, uint64_t key) {
jbauchde4db112017-05-31 13:09:18 -07001411 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1412 int fd = pdispatcher->GetDescriptor();
1413 RTC_DCHECK(fd != INVALID_SOCKET);
1414 if (fd == INVALID_SOCKET) {
1415 return;
1416 }
1417
1418 struct epoll_event event = {0};
1419 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001420 event.data.u64 = key;
jbauchde4db112017-05-31 13:09:18 -07001421 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &event);
1422 RTC_DCHECK_EQ(err, 0);
1423 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001424 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_MOD";
jbauchde4db112017-05-31 13:09:18 -07001425 }
1426}
1427
1428bool PhysicalSocketServer::WaitEpoll(int cmsWait) {
1429 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1430 int64_t tvWait = -1;
1431 int64_t tvStop = -1;
1432 if (cmsWait != kForever) {
1433 tvWait = cmsWait;
1434 tvStop = TimeAfter(cmsWait);
1435 }
1436
jbauchde4db112017-05-31 13:09:18 -07001437 fWait_ = true;
jbauchde4db112017-05-31 13:09:18 -07001438 while (fWait_) {
1439 // Wait then call handlers as appropriate
1440 // < 0 means error
1441 // 0 means timeout
1442 // > 0 means count of descriptors ready
Markus Handellb7c63ab2020-05-26 18:09:55 +02001443 int n = epoll_wait(epoll_fd_, epoll_events_.data(), epoll_events_.size(),
jbauchde4db112017-05-31 13:09:18 -07001444 static_cast<int>(tvWait));
1445 if (n < 0) {
1446 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001447 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll";
jbauchde4db112017-05-31 13:09:18 -07001448 return false;
1449 }
1450 // Else ignore the error and keep going. If this EINTR was for one of the
1451 // signals managed by this PhysicalSocketServer, the
1452 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1453 // iteration.
1454 } else if (n == 0) {
1455 // If timeout, return success
1456 return true;
1457 } else {
1458 // We have signaled descriptors
1459 CritScope cr(&crit_);
1460 for (int i = 0; i < n; ++i) {
1461 const epoll_event& event = epoll_events_[i];
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001462 uint64_t key = event.data.u64;
1463 if (!dispatcher_by_key_.count(key)) {
jbauchde4db112017-05-31 13:09:18 -07001464 // The dispatcher for this socket no longer exists.
1465 continue;
1466 }
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001467 Dispatcher* pdispatcher = dispatcher_by_key_.at(key);
jbauchde4db112017-05-31 13:09:18 -07001468
1469 bool readable = (event.events & (EPOLLIN | EPOLLPRI));
1470 bool writable = (event.events & EPOLLOUT);
1471 bool check_error = (event.events & (EPOLLRDHUP | EPOLLERR | EPOLLHUP));
1472
1473 ProcessEvents(pdispatcher, readable, writable, check_error);
1474 }
1475 }
1476
jbauchde4db112017-05-31 13:09:18 -07001477 if (cmsWait != kForever) {
1478 tvWait = TimeDiff(tvStop, TimeMillis());
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001479 if (tvWait <= 0) {
jbauchde4db112017-05-31 13:09:18 -07001480 // Return success on timeout.
1481 return true;
1482 }
1483 }
1484 }
1485
1486 return true;
1487}
1488
1489bool PhysicalSocketServer::WaitPoll(int cmsWait, Dispatcher* dispatcher) {
1490 RTC_DCHECK(dispatcher);
1491 int64_t tvWait = -1;
1492 int64_t tvStop = -1;
1493 if (cmsWait != kForever) {
1494 tvWait = cmsWait;
1495 tvStop = TimeAfter(cmsWait);
1496 }
1497
1498 fWait_ = true;
1499
1500 struct pollfd fds = {0};
1501 int fd = dispatcher->GetDescriptor();
1502 fds.fd = fd;
1503
1504 while (fWait_) {
1505 uint32_t ff = dispatcher->GetRequestedEvents();
1506 fds.events = 0;
1507 if (ff & (DE_READ | DE_ACCEPT)) {
1508 fds.events |= POLLIN;
1509 }
1510 if (ff & (DE_WRITE | DE_CONNECT)) {
1511 fds.events |= POLLOUT;
1512 }
1513 fds.revents = 0;
1514
1515 // Wait then call handlers as appropriate
1516 // < 0 means error
1517 // 0 means timeout
1518 // > 0 means count of descriptors ready
1519 int n = poll(&fds, 1, static_cast<int>(tvWait));
1520 if (n < 0) {
1521 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001522 RTC_LOG_E(LS_ERROR, EN, errno) << "poll";
jbauchde4db112017-05-31 13:09:18 -07001523 return false;
1524 }
1525 // Else ignore the error and keep going. If this EINTR was for one of the
1526 // signals managed by this PhysicalSocketServer, the
1527 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1528 // iteration.
1529 } else if (n == 0) {
1530 // If timeout, return success
1531 return true;
1532 } else {
1533 // We have signaled descriptors (should only be the passed dispatcher).
1534 RTC_DCHECK_EQ(n, 1);
1535 RTC_DCHECK_EQ(fds.fd, fd);
1536
1537 bool readable = (fds.revents & (POLLIN | POLLPRI));
1538 bool writable = (fds.revents & POLLOUT);
1539 bool check_error = (fds.revents & (POLLRDHUP | POLLERR | POLLHUP));
1540
1541 ProcessEvents(dispatcher, readable, writable, check_error);
1542 }
1543
1544 if (cmsWait != kForever) {
1545 tvWait = TimeDiff(tvStop, TimeMillis());
1546 if (tvWait < 0) {
1547 // Return success on timeout.
1548 return true;
1549 }
1550 }
1551 }
1552
1553 return true;
1554}
1555
1556#endif // WEBRTC_USE_EPOLL
1557
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001558#endif // WEBRTC_POSIX
1559
1560#if defined(WEBRTC_WIN)
1561bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001562 // We don't support reentrant waiting.
1563 RTC_DCHECK(!waiting_);
1564 ScopedSetTrue s(&waiting_);
1565
Honghai Zhang82d78622016-05-06 11:29:15 -07001566 int64_t cmsTotal = cmsWait;
1567 int64_t cmsElapsed = 0;
1568 int64_t msStart = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001569
1570 fWait_ = true;
1571 while (fWait_) {
1572 std::vector<WSAEVENT> events;
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001573 std::vector<uint64_t> event_owners;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001574
1575 events.push_back(socket_ev_);
1576
1577 {
1578 CritScope cr(&crit_);
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001579 // Get a snapshot of all current dispatchers; this is used to avoid the
1580 // ABA problem (see later comment) and avoids the dispatcher_by_key_
1581 // iterator being invalidated by calling CheckSignalClose, which may
1582 // remove the dispatcher from the list.
1583 current_dispatcher_keys_.clear();
1584 for (auto const& kv : dispatcher_by_key_) {
1585 current_dispatcher_keys_.push_back(kv.first);
1586 }
1587 for (uint64_t key : current_dispatcher_keys_) {
1588 if (!dispatcher_by_key_.count(key)) {
1589 continue;
1590 }
1591 Dispatcher* disp = dispatcher_by_key_.at(key);
1592 if (!disp)
1593 continue;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001594 if (!process_io && (disp != signal_wakeup_))
1595 continue;
1596 SOCKET s = disp->GetSocket();
1597 if (disp->CheckSignalClose()) {
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001598 // We just signalled close, don't poll this socket.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001599 } else if (s != INVALID_SOCKET) {
Yves Gerey665174f2018-06-19 15:03:05 +02001600 WSAEventSelect(s, events[0],
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001601 FlagsToEvents(disp->GetRequestedEvents()));
1602 } else {
1603 events.push_back(disp->GetWSAEvent());
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001604 event_owners.push_back(key);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001605 }
1606 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001607 }
1608
1609 // Which is shorter, the delay wait or the asked wait?
1610
Honghai Zhang82d78622016-05-06 11:29:15 -07001611 int64_t cmsNext;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001612 if (cmsWait == kForever) {
1613 cmsNext = cmsWait;
1614 } else {
Honghai Zhang82d78622016-05-06 11:29:15 -07001615 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001616 }
1617
1618 // Wait for one of the events to signal
Yves Gerey665174f2018-06-19 15:03:05 +02001619 DWORD dw =
1620 WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()), &events[0],
1621 false, static_cast<DWORD>(cmsNext), false);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001622
1623 if (dw == WSA_WAIT_FAILED) {
1624 // Failed?
jbauch095ae152015-12-18 01:39:55 -08001625 // TODO(pthatcher): need a better strategy than this!
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001626 WSAGetLastError();
nissec80e7412017-01-11 05:56:46 -08001627 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001628 return false;
1629 } else if (dw == WSA_WAIT_TIMEOUT) {
1630 // Timeout?
1631 return true;
1632 } else {
1633 // Figure out which one it is and call it
1634 CritScope cr(&crit_);
1635 int index = dw - WSA_WAIT_EVENT_0;
1636 if (index > 0) {
Yves Gerey665174f2018-06-19 15:03:05 +02001637 --index; // The first event is the socket event
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001638 uint64_t key = event_owners[index];
1639 if (!dispatcher_by_key_.count(key)) {
1640 // The dispatcher could have been removed while waiting for events.
1641 continue;
jbauchde4db112017-05-31 13:09:18 -07001642 }
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001643 Dispatcher* disp = dispatcher_by_key_.at(key);
1644 disp->OnPreEvent(0);
1645 disp->OnEvent(0, 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001646 } else if (process_io) {
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001647 // Iterate only on the dispatchers whose sockets were passed into
1648 // WSAEventSelect; this avoids the ABA problem (a socket being
1649 // destroyed and a new one created with the same SOCKET handle).
1650 for (uint64_t key : current_dispatcher_keys_) {
1651 if (!dispatcher_by_key_.count(key)) {
1652 continue;
1653 }
1654 Dispatcher* disp = dispatcher_by_key_.at(key);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001655 SOCKET s = disp->GetSocket();
1656 if (s == INVALID_SOCKET)
1657 continue;
1658
1659 WSANETWORKEVENTS wsaEvents;
1660 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1661 if (err == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001662 {
1663 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1664 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001665 RTC_LOG(WARNING)
1666 << "PhysicalSocketServer got FD_READ_BIT error "
1667 << wsaEvents.iErrorCode[FD_READ_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001668 }
1669 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1670 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001671 RTC_LOG(WARNING)
1672 << "PhysicalSocketServer got FD_WRITE_BIT error "
1673 << wsaEvents.iErrorCode[FD_WRITE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001674 }
1675 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1676 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001677 RTC_LOG(WARNING)
1678 << "PhysicalSocketServer got FD_CONNECT_BIT error "
1679 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001680 }
1681 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1682 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001683 RTC_LOG(WARNING)
1684 << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1685 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001686 }
1687 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1688 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001689 RTC_LOG(WARNING)
1690 << "PhysicalSocketServer got FD_CLOSE_BIT error "
1691 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001692 }
1693 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001694 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001695 int errcode = 0;
1696 if (wsaEvents.lNetworkEvents & FD_READ)
1697 ff |= DE_READ;
1698 if (wsaEvents.lNetworkEvents & FD_WRITE)
1699 ff |= DE_WRITE;
1700 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1701 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1702 ff |= DE_CONNECT;
1703 } else {
1704 ff |= DE_CLOSE;
1705 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1706 }
1707 }
1708 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1709 ff |= DE_ACCEPT;
1710 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1711 ff |= DE_CLOSE;
1712 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1713 }
1714 if (ff != 0) {
1715 disp->OnPreEvent(ff);
1716 disp->OnEvent(ff, errcode);
1717 }
1718 }
1719 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001720 }
1721
1722 // Reset the network event until new activity occurs
1723 WSAResetEvent(socket_ev_);
1724 }
1725
1726 // Break?
1727 if (!fWait_)
1728 break;
1729 cmsElapsed = TimeSince(msStart);
1730 if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
Yves Gerey665174f2018-06-19 15:03:05 +02001731 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001732 }
1733 }
1734
1735 // Done
1736 return true;
1737}
honghaizcec0a082016-01-15 14:49:09 -08001738#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001739
1740} // namespace rtc