blob: 7c01815d30b596cb2dfd19bf233df884089ce61c [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
Markus Handell9a21c492022-08-25 11:40:13 +000012#include <cstdint>
13
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000014#if defined(_MSC_VER) && _MSC_VER < 1300
Yves Gerey665174f2018-06-19 15:03:05 +020015#pragma warning(disable : 4786)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000016#endif
17
pbos@webrtc.org27e58982014-10-07 17:56:53 +000018#ifdef MEMORY_SANITIZER
19#include <sanitizer/msan_interface.h>
20#endif
21
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000022#if defined(WEBRTC_POSIX)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000023#include <fcntl.h>
Yves Gerey665174f2018-06-19 15:03:05 +020024#include <string.h>
jbauchde4db112017-05-31 13:09:18 -070025#if defined(WEBRTC_USE_EPOLL)
26// "poll" will be used to wait for the signal dispatcher.
27#include <poll.h>
28#endif
Yves Gerey665174f2018-06-19 15:03:05 +020029#include <sys/ioctl.h>
30#include <sys/select.h>
31#include <sys/time.h>
32#include <unistd.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000033#endif
34
35#if defined(WEBRTC_WIN)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000036#include <windows.h>
37#include <winsock2.h>
38#include <ws2tcpip.h>
39#undef SetPort
40#endif
41
Patrik Höglunda8005cf2017-12-13 16:05:42 +010042#include <errno.h>
43
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000044#include <algorithm>
45#include <map>
46
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "rtc_base/arraysize.h"
Steve Anton10542f22019-01-11 09:11:00 -080048#include "rtc_base/byte_order.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "rtc_base/checks.h"
50#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080051#include "rtc_base/network_monitor.h"
52#include "rtc_base/null_socket_server.h"
Niels Möller6d176022021-02-09 14:44:48 +010053#include "rtc_base/synchronization/mutex.h"
Steve Anton10542f22019-01-11 09:11:00 -080054#include "rtc_base/time_utils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000055
Emilio Cobos Álvarez68065502019-05-29 15:30:32 +020056#if defined(WEBRTC_LINUX)
57#include <linux/sockios.h>
58#endif
59
Patrik Höglunda8005cf2017-12-13 16:05:42 +010060#if defined(WEBRTC_WIN)
61#define LAST_SYSTEM_ERROR (::GetLastError())
62#elif defined(__native_client__) && __native_client__
63#define LAST_SYSTEM_ERROR (0)
64#elif defined(WEBRTC_POSIX)
65#define LAST_SYSTEM_ERROR (errno)
66#endif // WEBRTC_WIN
67
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000068#if defined(WEBRTC_POSIX)
69#include <netinet/tcp.h> // for TCP_NODELAY
Yves Gerey665174f2018-06-19 15:03:05 +020070#define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000071typedef void* SockOptArg;
Stefan Holmer9131efd2016-05-23 18:19:26 +020072
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000073#endif // WEBRTC_POSIX
74
Stefan Holmer3ebb3ef2016-05-23 20:26:11 +020075#if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) && !defined(__native_client__)
76
Stefan Holmer9131efd2016-05-23 18:19:26 +020077int64_t GetSocketRecvTimestamp(int socket) {
78 struct timeval tv_ioctl;
79 int ret = ioctl(socket, SIOCGSTAMP, &tv_ioctl);
80 if (ret != 0)
81 return -1;
82 int64_t timestamp =
83 rtc::kNumMicrosecsPerSec * static_cast<int64_t>(tv_ioctl.tv_sec) +
84 static_cast<int64_t>(tv_ioctl.tv_usec);
85 return timestamp;
86}
87
88#else
89
90int64_t GetSocketRecvTimestamp(int socket) {
91 return -1;
92}
93#endif
94
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000095#if defined(WEBRTC_WIN)
96typedef char* SockOptArg;
97#endif
98
jbauchde4db112017-05-31 13:09:18 -070099#if defined(WEBRTC_USE_EPOLL)
100// POLLRDHUP / EPOLLRDHUP are only defined starting with Linux 2.6.17.
101#if !defined(POLLRDHUP)
102#define POLLRDHUP 0x2000
103#endif
104#if !defined(EPOLLRDHUP)
105#define EPOLLRDHUP 0x2000
106#endif
107#endif
108
Taylor Brandstetter7b69a442020-08-20 23:43:13 +0000109namespace {
110class ScopedSetTrue {
111 public:
112 ScopedSetTrue(bool* value) : value_(value) {
113 RTC_DCHECK(!*value_);
114 *value_ = true;
115 }
116 ~ScopedSetTrue() { *value_ = false; }
117
118 private:
119 bool* value_;
120};
121} // namespace
122
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000123namespace rtc {
124
jbauch095ae152015-12-18 01:39:55 -0800125PhysicalSocket::PhysicalSocket(PhysicalSocketServer* ss, SOCKET s)
Yves Gerey665174f2018-06-19 15:03:05 +0200126 : ss_(ss),
127 s_(s),
128 error_(0),
129 state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED),
130 resolver_(nullptr) {
jbauch095ae152015-12-18 01:39:55 -0800131 if (s_ != INVALID_SOCKET) {
jbauch577f5dc2017-05-17 16:32:26 -0700132 SetEnabledEvents(DE_READ | DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000133
jbauch095ae152015-12-18 01:39:55 -0800134 int type = SOCK_STREAM;
135 socklen_t len = sizeof(type);
nissec16fa5e2017-02-07 07:18:43 -0800136 const int res =
137 getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len);
138 RTC_DCHECK_EQ(0, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000139 udp_ = (SOCK_DGRAM == type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000140 }
jbauch095ae152015-12-18 01:39:55 -0800141}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000142
jbauch095ae152015-12-18 01:39:55 -0800143PhysicalSocket::~PhysicalSocket() {
144 Close();
145}
146
147bool PhysicalSocket::Create(int family, int type) {
148 Close();
149 s_ = ::socket(family, type, 0);
150 udp_ = (SOCK_DGRAM == type);
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800151 family_ = family;
jbauch095ae152015-12-18 01:39:55 -0800152 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700153 if (udp_) {
154 SetEnabledEvents(DE_READ | DE_WRITE);
155 }
jbauch095ae152015-12-18 01:39:55 -0800156 return s_ != INVALID_SOCKET;
157}
158
159SocketAddress PhysicalSocket::GetLocalAddress() const {
Mirko Bonadei108a2f02019-11-20 19:43:38 +0100160 sockaddr_storage addr_storage = {};
jbauch095ae152015-12-18 01:39:55 -0800161 socklen_t addrlen = sizeof(addr_storage);
162 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
163 int result = ::getsockname(s_, addr, &addrlen);
164 SocketAddress address;
165 if (result >= 0) {
166 SocketAddressFromSockAddrStorage(addr_storage, &address);
167 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100168 RTC_LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
169 << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000170 }
jbauch095ae152015-12-18 01:39:55 -0800171 return address;
172}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000173
jbauch095ae152015-12-18 01:39:55 -0800174SocketAddress PhysicalSocket::GetRemoteAddress() const {
Mirko Bonadei108a2f02019-11-20 19:43:38 +0100175 sockaddr_storage addr_storage = {};
jbauch095ae152015-12-18 01:39:55 -0800176 socklen_t addrlen = sizeof(addr_storage);
177 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
178 int result = ::getpeername(s_, addr, &addrlen);
179 SocketAddress address;
180 if (result >= 0) {
181 SocketAddressFromSockAddrStorage(addr_storage, &address);
182 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100183 RTC_LOG(LS_WARNING)
184 << "GetRemoteAddress: unable to get remote addr, socket=" << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185 }
jbauch095ae152015-12-18 01:39:55 -0800186 return address;
187}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000188
jbauch095ae152015-12-18 01:39:55 -0800189int PhysicalSocket::Bind(const SocketAddress& bind_addr) {
deadbeefc874d122017-02-13 15:41:59 -0800190 SocketAddress copied_bind_addr = bind_addr;
191 // If a network binder is available, use it to bind a socket to an interface
192 // instead of bind(), since this is more reliable on an OS with a weak host
193 // model.
deadbeef9ffa13f2017-02-21 16:18:00 -0800194 if (ss_->network_binder() && !bind_addr.IsAnyIP()) {
deadbeefc874d122017-02-13 15:41:59 -0800195 NetworkBindingResult result =
196 ss_->network_binder()->BindSocketToNetwork(s_, bind_addr.ipaddr());
197 if (result == NetworkBindingResult::SUCCESS) {
198 // Since the network binder handled binding the socket to the desired
199 // network interface, we don't need to (and shouldn't) include an IP in
200 // the bind() call; bind() just needs to assign a port.
201 copied_bind_addr.SetIP(GetAnyIP(copied_bind_addr.ipaddr().family()));
202 } else if (result == NetworkBindingResult::NOT_IMPLEMENTED) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100203 RTC_LOG(LS_INFO) << "Can't bind socket to network because "
204 "network binding is not implemented for this OS.";
deadbeefc874d122017-02-13 15:41:59 -0800205 } else {
206 if (bind_addr.IsLoopbackIP()) {
207 // If we couldn't bind to a loopback IP (which should only happen in
208 // test scenarios), continue on. This may be expected behavior.
Paulina Hensmanb239a2e2020-03-31 16:16:11 +0200209 RTC_LOG(LS_VERBOSE) << "Binding socket to loopback address"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100210 << " failed; result: " << static_cast<int>(result);
deadbeefc874d122017-02-13 15:41:59 -0800211 } else {
Paulina Hensmanb239a2e2020-03-31 16:16:11 +0200212 RTC_LOG(LS_WARNING) << "Binding socket to network address"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100213 << " failed; result: " << static_cast<int>(result);
deadbeefc874d122017-02-13 15:41:59 -0800214 // If a network binding was attempted and failed, we should stop here
215 // and not try to use the socket. Otherwise, we may end up sending
216 // packets with an invalid source address.
217 // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=7026
218 return -1;
219 }
220 }
221 }
jbauch095ae152015-12-18 01:39:55 -0800222 sockaddr_storage addr_storage;
deadbeefc874d122017-02-13 15:41:59 -0800223 size_t len = copied_bind_addr.ToSockAddrStorage(&addr_storage);
jbauch095ae152015-12-18 01:39:55 -0800224 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
225 int err = ::bind(s_, addr, static_cast<int>(len));
226 UpdateLastError();
tfarinaa41ab932015-10-30 16:08:48 -0700227#if !defined(NDEBUG)
jbauch095ae152015-12-18 01:39:55 -0800228 if (0 == err) {
229 dbg_addr_ = "Bound @ ";
230 dbg_addr_.append(GetLocalAddress().ToString());
231 }
tfarinaa41ab932015-10-30 16:08:48 -0700232#endif
jbauch095ae152015-12-18 01:39:55 -0800233 return err;
234}
235
236int PhysicalSocket::Connect(const SocketAddress& addr) {
237 // TODO(pthatcher): Implicit creation is required to reconnect...
238 // ...but should we make it more explicit?
239 if (state_ != CS_CLOSED) {
240 SetError(EALREADY);
241 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000242 }
jbauch095ae152015-12-18 01:39:55 -0800243 if (addr.IsUnresolvedIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100244 RTC_LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
jbauch095ae152015-12-18 01:39:55 -0800245 resolver_ = new AsyncResolver();
246 resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult);
247 resolver_->Start(addr);
248 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000249 return 0;
250 }
251
jbauch095ae152015-12-18 01:39:55 -0800252 return DoConnect(addr);
253}
254
255int PhysicalSocket::DoConnect(const SocketAddress& connect_addr) {
Yves Gerey665174f2018-06-19 15:03:05 +0200256 if ((s_ == INVALID_SOCKET) && !Create(connect_addr.family(), SOCK_STREAM)) {
jbauch095ae152015-12-18 01:39:55 -0800257 return SOCKET_ERROR;
258 }
259 sockaddr_storage addr_storage;
260 size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
261 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
262 int err = ::connect(s_, addr, static_cast<int>(len));
263 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700264 uint8_t events = DE_READ | DE_WRITE;
jbauch095ae152015-12-18 01:39:55 -0800265 if (err == 0) {
266 state_ = CS_CONNECTED;
267 } else if (IsBlockingError(GetError())) {
268 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700269 events |= DE_CONNECT;
jbauch095ae152015-12-18 01:39:55 -0800270 } else {
271 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000272 }
273
jbauch577f5dc2017-05-17 16:32:26 -0700274 EnableEvents(events);
jbauch095ae152015-12-18 01:39:55 -0800275 return 0;
276}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000277
jbauch095ae152015-12-18 01:39:55 -0800278int PhysicalSocket::GetError() const {
Niels Möller6d176022021-02-09 14:44:48 +0100279 webrtc::MutexLock lock(&mutex_);
jbauch095ae152015-12-18 01:39:55 -0800280 return error_;
281}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000282
jbauch095ae152015-12-18 01:39:55 -0800283void PhysicalSocket::SetError(int error) {
Niels Möller6d176022021-02-09 14:44:48 +0100284 webrtc::MutexLock lock(&mutex_);
jbauch095ae152015-12-18 01:39:55 -0800285 error_ = error;
286}
287
Niels Möllerd0b88792021-08-12 10:32:30 +0200288Socket::ConnState PhysicalSocket::GetState() const {
jbauch095ae152015-12-18 01:39:55 -0800289 return state_;
290}
291
292int PhysicalSocket::GetOption(Option opt, int* value) {
293 int slevel;
294 int sopt;
295 if (TranslateOption(opt, &slevel, &sopt) == -1)
296 return -1;
297 socklen_t optlen = sizeof(*value);
298 int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800299 if (ret == -1) {
300 return -1;
301 }
302 if (opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000303#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800304 *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000305#endif
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800306 } else if (opt == OPT_DSCP) {
307#if defined(WEBRTC_POSIX)
308 // unshift DSCP value to get six most significant bits of IP DiffServ field
309 *value >>= 2;
310#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000311 }
jbauch095ae152015-12-18 01:39:55 -0800312 return ret;
313}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000314
jbauch095ae152015-12-18 01:39:55 -0800315int PhysicalSocket::SetOption(Option opt, int value) {
316 int slevel;
317 int sopt;
318 if (TranslateOption(opt, &slevel, &sopt) == -1)
319 return -1;
320 if (opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000321#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800322 value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000323#endif
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800324 } else if (opt == OPT_DSCP) {
325#if defined(WEBRTC_POSIX)
326 // shift DSCP value to fit six most significant bits of IP DiffServ field
327 value <<= 2;
328#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000329 }
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800330#if defined(WEBRTC_POSIX)
331 if (sopt == IPV6_TCLASS) {
332 // Set the IPv4 option in all cases to support dual-stack sockets.
Taylor Brandstetter9d269402020-11-25 15:24:53 -0800333 // Don't bother checking the return code, as this is expected to fail if
334 // it's not actually dual-stack.
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800335 ::setsockopt(s_, IPPROTO_IP, IP_TOS, (SockOptArg)&value, sizeof(value));
336 }
337#endif
Taylor Brandstetter9d269402020-11-25 15:24:53 -0800338 int result =
339 ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
340 if (result != 0) {
341 UpdateLastError();
342 }
343 return result;
jbauch095ae152015-12-18 01:39:55 -0800344}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000345
jbauch095ae152015-12-18 01:39:55 -0800346int PhysicalSocket::Send(const void* pv, size_t cb) {
Yves Gerey665174f2018-06-19 15:03:05 +0200347 int sent = DoSend(
348 s_, reinterpret_cast<const char*>(pv), static_cast<int>(cb),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000349#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800350 // Suppress SIGPIPE. Without this, attempting to send on a socket whose
351 // other end is closed will result in a SIGPIPE signal being raised to
352 // our process, which by default will terminate the process, which we
353 // don't want. By specifying this flag, we'll just get the error EPIPE
354 // instead and can handle the error gracefully.
355 MSG_NOSIGNAL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000356#else
jbauch095ae152015-12-18 01:39:55 -0800357 0
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000358#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200359 );
jbauch095ae152015-12-18 01:39:55 -0800360 UpdateLastError();
361 MaybeRemapSendError();
362 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800363 RTC_DCHECK(sent <= static_cast<int>(cb));
jbauchf2a2bf42016-02-03 16:45:32 -0800364 if ((sent > 0 && sent < static_cast<int>(cb)) ||
365 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700366 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000367 }
jbauch095ae152015-12-18 01:39:55 -0800368 return sent;
369}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000370
jbauch095ae152015-12-18 01:39:55 -0800371int PhysicalSocket::SendTo(const void* buffer,
372 size_t length,
373 const SocketAddress& addr) {
374 sockaddr_storage saddr;
375 size_t len = addr.ToSockAddrStorage(&saddr);
Yves Gerey665174f2018-06-19 15:03:05 +0200376 int sent =
377 DoSendTo(s_, static_cast<const char*>(buffer), static_cast<int>(length),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000378#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
Yves Gerey665174f2018-06-19 15:03:05 +0200379 // Suppress SIGPIPE. See above for explanation.
380 MSG_NOSIGNAL,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000381#else
Yves Gerey665174f2018-06-19 15:03:05 +0200382 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000383#endif
Yves Gerey665174f2018-06-19 15:03:05 +0200384 reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
jbauch095ae152015-12-18 01:39:55 -0800385 UpdateLastError();
386 MaybeRemapSendError();
387 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800388 RTC_DCHECK(sent <= static_cast<int>(length));
jbauchf2a2bf42016-02-03 16:45:32 -0800389 if ((sent > 0 && sent < static_cast<int>(length)) ||
390 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700391 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000392 }
jbauch095ae152015-12-18 01:39:55 -0800393 return sent;
394}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000395
Stefan Holmer9131efd2016-05-23 18:19:26 +0200396int PhysicalSocket::Recv(void* buffer, size_t length, int64_t* timestamp) {
Yves Gerey665174f2018-06-19 15:03:05 +0200397 int received =
398 ::recv(s_, static_cast<char*>(buffer), static_cast<int>(length), 0);
jbauch095ae152015-12-18 01:39:55 -0800399 if ((received == 0) && (length != 0)) {
400 // Note: on graceful shutdown, recv can return 0. In this case, we
401 // pretend it is blocking, and then signal close, so that simplifying
402 // assumptions can be made about Recv.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100403 RTC_LOG(LS_WARNING) << "EOF from socket; deferring close event";
jbauch095ae152015-12-18 01:39:55 -0800404 // Must turn this back on so that the select() loop will notice the close
405 // event.
jbauch577f5dc2017-05-17 16:32:26 -0700406 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800407 SetError(EWOULDBLOCK);
408 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000409 }
Stefan Holmer9131efd2016-05-23 18:19:26 +0200410 if (timestamp) {
411 *timestamp = GetSocketRecvTimestamp(s_);
412 }
jbauch095ae152015-12-18 01:39:55 -0800413 UpdateLastError();
414 int error = GetError();
415 bool success = (received >= 0) || IsBlockingError(error);
416 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700417 EnableEvents(DE_READ);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000418 }
jbauch095ae152015-12-18 01:39:55 -0800419 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100420 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000421 }
jbauch095ae152015-12-18 01:39:55 -0800422 return received;
423}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000424
jbauch095ae152015-12-18 01:39:55 -0800425int PhysicalSocket::RecvFrom(void* buffer,
426 size_t length,
Stefan Holmer9131efd2016-05-23 18:19:26 +0200427 SocketAddress* out_addr,
428 int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800429 sockaddr_storage addr_storage;
430 socklen_t addr_len = sizeof(addr_storage);
431 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
432 int received = ::recvfrom(s_, static_cast<char*>(buffer),
433 static_cast<int>(length), 0, addr, &addr_len);
Stefan Holmer9131efd2016-05-23 18:19:26 +0200434 if (timestamp) {
435 *timestamp = GetSocketRecvTimestamp(s_);
436 }
jbauch095ae152015-12-18 01:39:55 -0800437 UpdateLastError();
438 if ((received >= 0) && (out_addr != nullptr))
439 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
440 int error = GetError();
441 bool success = (received >= 0) || IsBlockingError(error);
442 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700443 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800444 }
445 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100446 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
jbauch095ae152015-12-18 01:39:55 -0800447 }
448 return received;
449}
450
451int PhysicalSocket::Listen(int backlog) {
452 int err = ::listen(s_, backlog);
453 UpdateLastError();
454 if (err == 0) {
455 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700456 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800457#if !defined(NDEBUG)
458 dbg_addr_ = "Listening @ ";
459 dbg_addr_.append(GetLocalAddress().ToString());
460#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000461 }
jbauch095ae152015-12-18 01:39:55 -0800462 return err;
463}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000464
Niels Möllerd0b88792021-08-12 10:32:30 +0200465Socket* PhysicalSocket::Accept(SocketAddress* out_addr) {
jbauch095ae152015-12-18 01:39:55 -0800466 // Always re-subscribe DE_ACCEPT to make sure new incoming connections will
467 // trigger an event even if DoAccept returns an error here.
jbauch577f5dc2017-05-17 16:32:26 -0700468 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800469 sockaddr_storage addr_storage;
470 socklen_t addr_len = sizeof(addr_storage);
471 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
472 SOCKET s = DoAccept(s_, addr, &addr_len);
473 UpdateLastError();
474 if (s == INVALID_SOCKET)
475 return nullptr;
476 if (out_addr != nullptr)
477 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
478 return ss_->WrapSocket(s);
479}
480
481int PhysicalSocket::Close() {
482 if (s_ == INVALID_SOCKET)
483 return 0;
484 int err = ::closesocket(s_);
485 UpdateLastError();
486 s_ = INVALID_SOCKET;
487 state_ = CS_CLOSED;
jbauch577f5dc2017-05-17 16:32:26 -0700488 SetEnabledEvents(0);
jbauch095ae152015-12-18 01:39:55 -0800489 if (resolver_) {
490 resolver_->Destroy(false);
491 resolver_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000492 }
jbauch095ae152015-12-18 01:39:55 -0800493 return err;
494}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000495
jbauch095ae152015-12-18 01:39:55 -0800496SOCKET PhysicalSocket::DoAccept(SOCKET socket,
497 sockaddr* addr,
498 socklen_t* addrlen) {
499 return ::accept(socket, addr, addrlen);
500}
501
jbauchf2a2bf42016-02-03 16:45:32 -0800502int PhysicalSocket::DoSend(SOCKET socket, const char* buf, int len, int flags) {
503 return ::send(socket, buf, len, flags);
504}
505
506int PhysicalSocket::DoSendTo(SOCKET socket,
507 const char* buf,
508 int len,
509 int flags,
510 const struct sockaddr* dest_addr,
511 socklen_t addrlen) {
512 return ::sendto(socket, buf, len, flags, dest_addr, addrlen);
513}
514
jbauch095ae152015-12-18 01:39:55 -0800515void PhysicalSocket::OnResolveResult(AsyncResolverInterface* resolver) {
516 if (resolver != resolver_) {
517 return;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000518 }
519
jbauch095ae152015-12-18 01:39:55 -0800520 int error = resolver_->GetError();
521 if (error == 0) {
522 error = DoConnect(resolver_->address());
523 } else {
524 Close();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000525 }
526
jbauch095ae152015-12-18 01:39:55 -0800527 if (error) {
528 SetError(error);
529 SignalCloseEvent(this, error);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000530 }
jbauch095ae152015-12-18 01:39:55 -0800531}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000532
jbauch095ae152015-12-18 01:39:55 -0800533void PhysicalSocket::UpdateLastError() {
Patrik Höglunda8005cf2017-12-13 16:05:42 +0100534 SetError(LAST_SYSTEM_ERROR);
jbauch095ae152015-12-18 01:39:55 -0800535}
536
537void PhysicalSocket::MaybeRemapSendError() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000538#if defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800539 // https://developer.apple.com/library/mac/documentation/Darwin/
540 // Reference/ManPages/man2/sendto.2.html
541 // ENOBUFS - The output queue for a network interface is full.
542 // This generally indicates that the interface has stopped sending,
543 // but may be caused by transient congestion.
544 if (GetError() == ENOBUFS) {
545 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000546 }
jbauch095ae152015-12-18 01:39:55 -0800547#endif
548}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000549
jbauch577f5dc2017-05-17 16:32:26 -0700550void PhysicalSocket::SetEnabledEvents(uint8_t events) {
551 enabled_events_ = events;
552}
553
554void PhysicalSocket::EnableEvents(uint8_t events) {
555 enabled_events_ |= events;
556}
557
558void PhysicalSocket::DisableEvents(uint8_t events) {
559 enabled_events_ &= ~events;
560}
561
jbauch095ae152015-12-18 01:39:55 -0800562int PhysicalSocket::TranslateOption(Option opt, int* slevel, int* sopt) {
563 switch (opt) {
564 case OPT_DONTFRAGMENT:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000565#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800566 *slevel = IPPROTO_IP;
567 *sopt = IP_DONTFRAGMENT;
568 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000569#elif defined(WEBRTC_MAC) || defined(BSD) || defined(__native_client__)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100570 RTC_LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
jbauch095ae152015-12-18 01:39:55 -0800571 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000572#elif defined(WEBRTC_POSIX)
jbauch095ae152015-12-18 01:39:55 -0800573 *slevel = IPPROTO_IP;
574 *sopt = IP_MTU_DISCOVER;
575 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000576#endif
jbauch095ae152015-12-18 01:39:55 -0800577 case OPT_RCVBUF:
578 *slevel = SOL_SOCKET;
579 *sopt = SO_RCVBUF;
580 break;
581 case OPT_SNDBUF:
582 *slevel = SOL_SOCKET;
583 *sopt = SO_SNDBUF;
584 break;
585 case OPT_NODELAY:
586 *slevel = IPPROTO_TCP;
587 *sopt = TCP_NODELAY;
588 break;
589 case OPT_DSCP:
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800590#if defined(WEBRTC_POSIX)
591 if (family_ == AF_INET6) {
592 *slevel = IPPROTO_IPV6;
593 *sopt = IPV6_TCLASS;
594 } else {
595 *slevel = IPPROTO_IP;
596 *sopt = IP_TOS;
597 }
598 break;
599#else
Mirko Bonadei675513b2017-11-09 11:09:25 +0100600 RTC_LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
jbauch095ae152015-12-18 01:39:55 -0800601 return -1;
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800602#endif
jbauch095ae152015-12-18 01:39:55 -0800603 case OPT_RTP_SENDTIME_EXTN_ID:
604 return -1; // No logging is necessary as this not a OS socket option.
605 default:
Artem Titovd3251962021-11-15 16:57:07 +0100606 RTC_DCHECK_NOTREACHED();
jbauch095ae152015-12-18 01:39:55 -0800607 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000608 }
jbauch095ae152015-12-18 01:39:55 -0800609 return 0;
610}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000611
Yves Gerey665174f2018-06-19 15:03:05 +0200612SocketDispatcher::SocketDispatcher(PhysicalSocketServer* ss)
jbauch4331fcd2016-01-06 22:20:28 -0800613#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200614 : PhysicalSocket(ss),
615 id_(0),
616 signal_close_(false)
jbauch4331fcd2016-01-06 22:20:28 -0800617#else
Yves Gerey665174f2018-06-19 15:03:05 +0200618 : PhysicalSocket(ss)
jbauch4331fcd2016-01-06 22:20:28 -0800619#endif
620{
621}
622
Yves Gerey665174f2018-06-19 15:03:05 +0200623SocketDispatcher::SocketDispatcher(SOCKET s, PhysicalSocketServer* ss)
jbauch4331fcd2016-01-06 22:20:28 -0800624#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200625 : PhysicalSocket(ss, s),
626 id_(0),
627 signal_close_(false)
jbauch4331fcd2016-01-06 22:20:28 -0800628#else
Yves Gerey665174f2018-06-19 15:03:05 +0200629 : PhysicalSocket(ss, s)
jbauch4331fcd2016-01-06 22:20:28 -0800630#endif
631{
632}
633
634SocketDispatcher::~SocketDispatcher() {
635 Close();
636}
637
638bool SocketDispatcher::Initialize() {
nisseede5da42017-01-12 05:15:36 -0800639 RTC_DCHECK(s_ != INVALID_SOCKET);
Yves Gerey665174f2018-06-19 15:03:05 +0200640// Must be a non-blocking
jbauch4331fcd2016-01-06 22:20:28 -0800641#if defined(WEBRTC_WIN)
642 u_long argp = 1;
643 ioctlsocket(s_, FIONBIO, &argp);
644#elif defined(WEBRTC_POSIX)
645 fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
646#endif
deadbeefeae45642017-05-26 16:27:09 -0700647#if defined(WEBRTC_IOS)
648 // iOS may kill sockets when the app is moved to the background
649 // (specifically, if the app doesn't use the "voip" UIBackgroundMode). When
650 // we attempt to write to such a socket, SIGPIPE will be raised, which by
651 // default will terminate the process, which we don't want. By specifying
652 // this socket option, SIGPIPE will be disabled for the socket.
653 int value = 1;
654 ::setsockopt(s_, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value));
655#endif
jbauch4331fcd2016-01-06 22:20:28 -0800656 ss_->Add(this);
657 return true;
658}
659
660bool SocketDispatcher::Create(int type) {
661 return Create(AF_INET, type);
662}
663
664bool SocketDispatcher::Create(int family, int type) {
665 // Change the socket to be non-blocking.
666 if (!PhysicalSocket::Create(family, type))
667 return false;
668
669 if (!Initialize())
670 return false;
671
672#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200673 do {
674 id_ = ++next_id_;
675 } while (id_ == 0);
jbauch4331fcd2016-01-06 22:20:28 -0800676#endif
677 return true;
678}
679
680#if defined(WEBRTC_WIN)
681
682WSAEVENT SocketDispatcher::GetWSAEvent() {
683 return WSA_INVALID_EVENT;
684}
685
686SOCKET SocketDispatcher::GetSocket() {
687 return s_;
688}
689
690bool SocketDispatcher::CheckSignalClose() {
691 if (!signal_close_)
692 return false;
693
694 char ch;
695 if (recv(s_, &ch, 1, MSG_PEEK) > 0)
696 return false;
697
698 state_ = CS_CLOSED;
699 signal_close_ = false;
700 SignalCloseEvent(this, signal_err_);
701 return true;
702}
703
704int SocketDispatcher::next_id_ = 0;
705
706#elif defined(WEBRTC_POSIX)
707
708int SocketDispatcher::GetDescriptor() {
709 return s_;
710}
711
712bool SocketDispatcher::IsDescriptorClosed() {
deadbeeffaedf7f2017-02-09 15:09:22 -0800713 if (udp_) {
714 // The MSG_PEEK trick doesn't work for UDP, since (at least in some
715 // circumstances) it requires reading an entire UDP packet, which would be
Artem Titov96e3b992021-07-26 16:03:14 +0200716 // bad for performance here. So, just check whether `s_` has been closed,
deadbeeffaedf7f2017-02-09 15:09:22 -0800717 // which should be sufficient.
718 return s_ == INVALID_SOCKET;
719 }
jbauch4331fcd2016-01-06 22:20:28 -0800720 // We don't have a reliable way of distinguishing end-of-stream
721 // from readability. So test on each readable call. Is this
722 // inefficient? Probably.
723 char ch;
Taylor Brandstetter3041eb22021-11-02 19:46:40 +0000724 ssize_t res;
725 // Retry if the system call was interrupted.
726 do {
727 res = ::recv(s_, &ch, 1, MSG_PEEK);
728 } while (res < 0 && errno == EINTR);
jbauch4331fcd2016-01-06 22:20:28 -0800729 if (res > 0) {
730 // Data available, so not closed.
731 return false;
732 } else if (res == 0) {
733 // EOF, so closed.
734 return true;
735 } else { // error
736 switch (errno) {
737 // Returned if we've already closed s_.
738 case EBADF:
Taylor Brandstetter3041eb22021-11-02 19:46:40 +0000739 // This is dangerous: if we keep attempting to access a FD after close,
740 // it could be reopened by something else making us think it's still
741 // open. Note that this is only a DCHECK.
Artem Titovd3251962021-11-15 16:57:07 +0100742 RTC_DCHECK_NOTREACHED();
Taylor Brandstetter3041eb22021-11-02 19:46:40 +0000743 return true;
jbauch4331fcd2016-01-06 22:20:28 -0800744 // Returned during ungraceful peer shutdown.
745 case ECONNRESET:
746 return true;
Taylor Brandstetter3041eb22021-11-02 19:46:40 +0000747 case ECONNABORTED:
748 return true;
749 case EPIPE:
750 return true;
deadbeeffaedf7f2017-02-09 15:09:22 -0800751 // The normal blocking error; don't log anything.
752 case EWOULDBLOCK:
deadbeeffaedf7f2017-02-09 15:09:22 -0800753 return false;
jbauch4331fcd2016-01-06 22:20:28 -0800754 default:
755 // Assume that all other errors are just blocking errors, meaning the
756 // connection is still good but we just can't read from it right now.
757 // This should only happen when connecting (and at most once), because
758 // in all other cases this function is only called if the file
759 // descriptor is already known to be in the readable state. However,
760 // it's not necessary a problem if we spuriously interpret a
761 // "connection lost"-type error as a blocking error, because typically
762 // the next recv() will get EOF, so we'll still eventually notice that
763 // the socket is closed.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100764 RTC_LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
jbauch4331fcd2016-01-06 22:20:28 -0800765 return false;
766 }
767 }
768}
769
Yves Gerey665174f2018-06-19 15:03:05 +0200770#endif // WEBRTC_POSIX
jbauch4331fcd2016-01-06 22:20:28 -0800771
772uint32_t SocketDispatcher::GetRequestedEvents() {
jbauch577f5dc2017-05-17 16:32:26 -0700773 return enabled_events();
jbauch4331fcd2016-01-06 22:20:28 -0800774}
775
jbauch4331fcd2016-01-06 22:20:28 -0800776#if defined(WEBRTC_WIN)
777
778void SocketDispatcher::OnEvent(uint32_t ff, int err) {
Niels Möller21347452021-02-12 11:19:52 +0100779 if ((ff & DE_CONNECT) != 0)
780 state_ = CS_CONNECTED;
781
782 // We set CS_CLOSED from CheckSignalClose.
783
jbauch4331fcd2016-01-06 22:20:28 -0800784 int cache_id = id_;
785 // Make sure we deliver connect/accept first. Otherwise, consumers may see
786 // something like a READ followed by a CONNECT, which would be odd.
787 if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
788 if (ff != DE_CONNECT)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100789 RTC_LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
jbauch577f5dc2017-05-17 16:32:26 -0700790 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800791#if !defined(NDEBUG)
792 dbg_addr_ = "Connected @ ";
793 dbg_addr_.append(GetRemoteAddress().ToString());
794#endif
795 SignalConnectEvent(this);
796 }
797 if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700798 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800799 SignalReadEvent(this);
800 }
801 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700802 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800803 SignalReadEvent(this);
804 }
805 if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700806 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800807 SignalWriteEvent(this);
808 }
809 if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
810 signal_close_ = true;
811 signal_err_ = err;
812 }
813}
814
815#elif defined(WEBRTC_POSIX)
816
817void SocketDispatcher::OnEvent(uint32_t ff, int err) {
Niels Möller21347452021-02-12 11:19:52 +0100818 if ((ff & DE_CONNECT) != 0)
819 state_ = CS_CONNECTED;
820
821 if ((ff & DE_CLOSE) != 0)
822 state_ = CS_CLOSED;
823
jbauchde4db112017-05-31 13:09:18 -0700824#if defined(WEBRTC_USE_EPOLL)
825 // Remember currently enabled events so we can combine multiple changes
826 // into one update call later.
827 // The signal handlers might re-enable events disabled here, so we can't
828 // keep a list of events to disable at the end of the method. This list
829 // would not be updated with the events enabled by the signal handlers.
830 StartBatchedEventUpdates();
831#endif
jbauch4331fcd2016-01-06 22:20:28 -0800832 // Make sure we deliver connect/accept first. Otherwise, consumers may see
833 // something like a READ followed by a CONNECT, which would be odd.
834 if ((ff & DE_CONNECT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700835 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800836 SignalConnectEvent(this);
837 }
838 if ((ff & DE_ACCEPT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700839 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800840 SignalReadEvent(this);
841 }
842 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700843 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800844 SignalReadEvent(this);
845 }
846 if ((ff & DE_WRITE) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700847 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800848 SignalWriteEvent(this);
849 }
850 if ((ff & DE_CLOSE) != 0) {
851 // The socket is now dead to us, so stop checking it.
jbauch577f5dc2017-05-17 16:32:26 -0700852 SetEnabledEvents(0);
jbauch4331fcd2016-01-06 22:20:28 -0800853 SignalCloseEvent(this, err);
854 }
jbauchde4db112017-05-31 13:09:18 -0700855#if defined(WEBRTC_USE_EPOLL)
856 FinishBatchedEventUpdates();
857#endif
jbauch4331fcd2016-01-06 22:20:28 -0800858}
859
Yves Gerey665174f2018-06-19 15:03:05 +0200860#endif // WEBRTC_POSIX
jbauch4331fcd2016-01-06 22:20:28 -0800861
jbauchde4db112017-05-31 13:09:18 -0700862#if defined(WEBRTC_USE_EPOLL)
863
Taylor Brandstetter7b69a442020-08-20 23:43:13 +0000864inline static int GetEpollEvents(uint32_t ff) {
jbauchde4db112017-05-31 13:09:18 -0700865 int events = 0;
866 if (ff & (DE_READ | DE_ACCEPT)) {
867 events |= EPOLLIN;
868 }
869 if (ff & (DE_WRITE | DE_CONNECT)) {
870 events |= EPOLLOUT;
871 }
872 return events;
873}
874
875void SocketDispatcher::StartBatchedEventUpdates() {
876 RTC_DCHECK_EQ(saved_enabled_events_, -1);
877 saved_enabled_events_ = enabled_events();
878}
879
880void SocketDispatcher::FinishBatchedEventUpdates() {
881 RTC_DCHECK_NE(saved_enabled_events_, -1);
882 uint8_t old_events = static_cast<uint8_t>(saved_enabled_events_);
883 saved_enabled_events_ = -1;
884 MaybeUpdateDispatcher(old_events);
885}
886
887void SocketDispatcher::MaybeUpdateDispatcher(uint8_t old_events) {
888 if (GetEpollEvents(enabled_events()) != GetEpollEvents(old_events) &&
889 saved_enabled_events_ == -1) {
890 ss_->Update(this);
891 }
892}
893
894void SocketDispatcher::SetEnabledEvents(uint8_t events) {
895 uint8_t old_events = enabled_events();
896 PhysicalSocket::SetEnabledEvents(events);
897 MaybeUpdateDispatcher(old_events);
898}
899
900void SocketDispatcher::EnableEvents(uint8_t events) {
901 uint8_t old_events = enabled_events();
902 PhysicalSocket::EnableEvents(events);
903 MaybeUpdateDispatcher(old_events);
904}
905
906void SocketDispatcher::DisableEvents(uint8_t events) {
907 uint8_t old_events = enabled_events();
908 PhysicalSocket::DisableEvents(events);
909 MaybeUpdateDispatcher(old_events);
910}
911
912#endif // WEBRTC_USE_EPOLL
913
jbauch4331fcd2016-01-06 22:20:28 -0800914int SocketDispatcher::Close() {
915 if (s_ == INVALID_SOCKET)
916 return 0;
917
918#if defined(WEBRTC_WIN)
919 id_ = 0;
920 signal_close_ = false;
921#endif
mmorrison25eeda12020-04-07 16:13:13 -0600922#if defined(WEBRTC_USE_EPOLL)
923 // If we're batching events, the socket can be closed and reopened
924 // during the batch. Set saved_enabled_events_ to 0 here so the new
925 // socket, if any, has the correct old events bitfield
926 if (saved_enabled_events_ != -1) {
927 saved_enabled_events_ = 0;
928 }
929#endif
jbauch4331fcd2016-01-06 22:20:28 -0800930 ss_->Remove(this);
931 return PhysicalSocket::Close();
932}
933
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000934#if defined(WEBRTC_POSIX)
Niels Möller21347452021-02-12 11:19:52 +0100935// Sets the value of a boolean value to false when signaled.
936class Signaler : public Dispatcher {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000937 public:
Niels Möller21347452021-02-12 11:19:52 +0100938 Signaler(PhysicalSocketServer* ss, bool& flag_to_clear)
939 : ss_(ss),
940 afd_([] {
941 std::array<int, 2> afd = {-1, -1};
942
943 if (pipe(afd.data()) < 0) {
Harald Alvestrand5f341302021-11-24 10:01:32 +0000944 RTC_LOG(LS_ERROR) << "pipe failed";
Niels Möller21347452021-02-12 11:19:52 +0100945 }
946 return afd;
947 }()),
948 fSignaled_(false),
949 flag_to_clear_(flag_to_clear) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000950 ss_->Add(this);
951 }
952
Niels Möller21347452021-02-12 11:19:52 +0100953 ~Signaler() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000954 ss_->Remove(this);
955 close(afd_[0]);
956 close(afd_[1]);
957 }
958
959 virtual void Signal() {
Niels Möller6d176022021-02-09 14:44:48 +0100960 webrtc::MutexLock lock(&mutex_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000961 if (!fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200962 const uint8_t b[1] = {0};
nissec16fa5e2017-02-07 07:18:43 -0800963 const ssize_t res = write(afd_[1], b, sizeof(b));
964 RTC_DCHECK_EQ(1, res);
965 fSignaled_ = true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000966 }
967 }
968
Peter Boström0c4e06b2015-10-07 12:23:21 +0200969 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000970
Niels Möller21347452021-02-12 11:19:52 +0100971 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000972 // It is not possible to perfectly emulate an auto-resetting event with
973 // pipes. This simulates it by resetting before the event is handled.
974
Niels Möller6d176022021-02-09 14:44:48 +0100975 webrtc::MutexLock lock(&mutex_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000976 if (fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200977 uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
nissec16fa5e2017-02-07 07:18:43 -0800978 const ssize_t res = read(afd_[0], b, sizeof(b));
979 RTC_DCHECK_EQ(1, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000980 fSignaled_ = false;
981 }
Niels Möller21347452021-02-12 11:19:52 +0100982 flag_to_clear_ = false;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000983 }
984
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000985 int GetDescriptor() override { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000986
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000987 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000988
989 private:
Niels Möller6d176022021-02-09 14:44:48 +0100990 PhysicalSocketServer* const ss_;
Niels Möller21347452021-02-12 11:19:52 +0100991 const std::array<int, 2> afd_;
Niels Möller6d176022021-02-09 14:44:48 +0100992 bool fSignaled_ RTC_GUARDED_BY(mutex_);
993 webrtc::Mutex mutex_;
Niels Möller21347452021-02-12 11:19:52 +0100994 bool& flag_to_clear_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000995};
996
Yves Gerey665174f2018-06-19 15:03:05 +0200997#endif // WEBRTC_POSIX
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000998
999#if defined(WEBRTC_WIN)
Peter Boström0c4e06b2015-10-07 12:23:21 +02001000static uint32_t FlagsToEvents(uint32_t events) {
1001 uint32_t ffFD = FD_CLOSE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001002 if (events & DE_READ)
1003 ffFD |= FD_READ;
1004 if (events & DE_WRITE)
1005 ffFD |= FD_WRITE;
1006 if (events & DE_CONNECT)
1007 ffFD |= FD_CONNECT;
1008 if (events & DE_ACCEPT)
1009 ffFD |= FD_ACCEPT;
1010 return ffFD;
1011}
1012
Niels Möller21347452021-02-12 11:19:52 +01001013// Sets the value of a boolean value to false when signaled.
1014class Signaler : public Dispatcher {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001015 public:
Niels Möller21347452021-02-12 11:19:52 +01001016 Signaler(PhysicalSocketServer* ss, bool& flag_to_clear)
1017 : ss_(ss), flag_to_clear_(flag_to_clear) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001018 hev_ = WSACreateEvent();
1019 if (hev_) {
1020 ss_->Add(this);
1021 }
1022 }
1023
Niels Möller21347452021-02-12 11:19:52 +01001024 ~Signaler() override {
deadbeef37f5ecf2017-02-27 14:06:41 -08001025 if (hev_ != nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001026 ss_->Remove(this);
1027 WSACloseEvent(hev_);
deadbeef37f5ecf2017-02-27 14:06:41 -08001028 hev_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001029 }
1030 }
1031
1032 virtual void Signal() {
deadbeef37f5ecf2017-02-27 14:06:41 -08001033 if (hev_ != nullptr)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001034 WSASetEvent(hev_);
1035 }
1036
Steve Anton9de3aac2017-10-24 10:08:26 -07001037 uint32_t GetRequestedEvents() override { return 0; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001038
Niels Möller21347452021-02-12 11:19:52 +01001039 void OnEvent(uint32_t ff, int err) override {
1040 WSAResetEvent(hev_);
1041 flag_to_clear_ = false;
1042 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001043
Steve Anton9de3aac2017-10-24 10:08:26 -07001044 WSAEVENT GetWSAEvent() override { return hev_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001045
Steve Anton9de3aac2017-10-24 10:08:26 -07001046 SOCKET GetSocket() override { return INVALID_SOCKET; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001047
Steve Anton9de3aac2017-10-24 10:08:26 -07001048 bool CheckSignalClose() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001049
Steve Anton9de3aac2017-10-24 10:08:26 -07001050 private:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001051 PhysicalSocketServer* ss_;
1052 WSAEVENT hev_;
Niels Möller21347452021-02-12 11:19:52 +01001053 bool& flag_to_clear_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001054};
honghaizcec0a082016-01-15 14:49:09 -08001055#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001056
Niels Möller611fba42020-05-13 14:42:22 +02001057PhysicalSocketServer::PhysicalSocketServer()
1058 :
jbauchde4db112017-05-31 13:09:18 -07001059#if defined(WEBRTC_USE_EPOLL)
Niels Möller611fba42020-05-13 14:42:22 +02001060 // Since Linux 2.6.8, the size argument is ignored, but must be greater
1061 // than zero. Before that the size served as hint to the kernel for the
1062 // amount of space to initially allocate in internal data structures.
1063 epoll_fd_(epoll_create(FD_SETSIZE)),
1064#endif
1065#if defined(WEBRTC_WIN)
1066 socket_ev_(WSACreateEvent()),
1067#endif
1068 fWait_(false) {
1069#if defined(WEBRTC_USE_EPOLL)
jbauchde4db112017-05-31 13:09:18 -07001070 if (epoll_fd_ == -1) {
1071 // Not an error, will fall back to "select" below.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001072 RTC_LOG_E(LS_WARNING, EN, errno) << "epoll_create";
Niels Möller611fba42020-05-13 14:42:22 +02001073 // Note that -1 == INVALID_SOCKET, the alias used by later checks.
jbauchde4db112017-05-31 13:09:18 -07001074 }
1075#endif
Niels Möller21347452021-02-12 11:19:52 +01001076 // The `fWait_` flag to be cleared by the Signaler.
1077 signal_wakeup_ = new Signaler(this, fWait_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001078}
1079
1080PhysicalSocketServer::~PhysicalSocketServer() {
1081#if defined(WEBRTC_WIN)
1082 WSACloseEvent(socket_ev_);
1083#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001084 delete signal_wakeup_;
jbauchde4db112017-05-31 13:09:18 -07001085#if defined(WEBRTC_USE_EPOLL)
1086 if (epoll_fd_ != INVALID_SOCKET) {
1087 close(epoll_fd_);
1088 }
1089#endif
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001090 RTC_DCHECK(dispatcher_by_key_.empty());
1091 RTC_DCHECK(key_by_dispatcher_.empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001092}
1093
1094void PhysicalSocketServer::WakeUp() {
1095 signal_wakeup_->Signal();
1096}
1097
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001098Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001099 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1100 if (dispatcher->Create(family, type)) {
1101 return dispatcher;
1102 } else {
1103 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001104 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001105 }
1106}
1107
Niels Möllerd0b88792021-08-12 10:32:30 +02001108Socket* PhysicalSocketServer::WrapSocket(SOCKET s) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001109 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1110 if (dispatcher->Initialize()) {
1111 return dispatcher;
1112 } else {
1113 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001114 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001115 }
1116}
1117
Yves Gerey665174f2018-06-19 15:03:05 +02001118void PhysicalSocketServer::Add(Dispatcher* pdispatcher) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001119 CritScope cs(&crit_);
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001120 if (key_by_dispatcher_.count(pdispatcher)) {
1121 RTC_LOG(LS_WARNING)
1122 << "PhysicalSocketServer asked to add a duplicate dispatcher.";
1123 return;
jbauchde4db112017-05-31 13:09:18 -07001124 }
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001125 uint64_t key = next_dispatcher_key_++;
1126 dispatcher_by_key_.emplace(key, pdispatcher);
1127 key_by_dispatcher_.emplace(pdispatcher, key);
jbauchde4db112017-05-31 13:09:18 -07001128#if defined(WEBRTC_USE_EPOLL)
1129 if (epoll_fd_ != INVALID_SOCKET) {
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001130 AddEpoll(pdispatcher, key);
jbauchde4db112017-05-31 13:09:18 -07001131 }
1132#endif // WEBRTC_USE_EPOLL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001133}
1134
Yves Gerey665174f2018-06-19 15:03:05 +02001135void PhysicalSocketServer::Remove(Dispatcher* pdispatcher) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001136 CritScope cs(&crit_);
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001137 if (!key_by_dispatcher_.count(pdispatcher)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001138 RTC_LOG(LS_WARNING)
1139 << "PhysicalSocketServer asked to remove a unknown "
Jonas Olssonb2b20312020-01-14 12:11:31 +01001140 "dispatcher, potentially from a duplicate call to Add.";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001141 return;
1142 }
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001143 uint64_t key = key_by_dispatcher_.at(pdispatcher);
1144 key_by_dispatcher_.erase(pdispatcher);
1145 dispatcher_by_key_.erase(key);
jbauchde4db112017-05-31 13:09:18 -07001146#if defined(WEBRTC_USE_EPOLL)
1147 if (epoll_fd_ != INVALID_SOCKET) {
1148 RemoveEpoll(pdispatcher);
1149 }
1150#endif // WEBRTC_USE_EPOLL
1151}
1152
1153void PhysicalSocketServer::Update(Dispatcher* pdispatcher) {
1154#if defined(WEBRTC_USE_EPOLL)
1155 if (epoll_fd_ == INVALID_SOCKET) {
1156 return;
1157 }
1158
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001159 // Don't update dispatchers that haven't yet been added.
jbauchde4db112017-05-31 13:09:18 -07001160 CritScope cs(&crit_);
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001161 if (!key_by_dispatcher_.count(pdispatcher)) {
jbauchde4db112017-05-31 13:09:18 -07001162 return;
1163 }
1164
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001165 UpdateEpoll(pdispatcher, key_by_dispatcher_.at(pdispatcher));
jbauchde4db112017-05-31 13:09:18 -07001166#endif
1167}
1168
Markus Handell9a21c492022-08-25 11:40:13 +00001169int PhysicalSocketServer::ToCmsWait(webrtc::TimeDelta max_wait_duration) {
1170 return max_wait_duration == Event::kForever
1171 ? kForeverMs
1172 : max_wait_duration.RoundUpTo(webrtc::TimeDelta::Millis(1)).ms();
1173}
1174
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001175#if defined(WEBRTC_POSIX)
jbauchde4db112017-05-31 13:09:18 -07001176
Markus Handell9a21c492022-08-25 11:40:13 +00001177bool PhysicalSocketServer::Wait(webrtc::TimeDelta max_wait_duration,
1178 bool process_io) {
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001179 // We don't support reentrant waiting.
1180 RTC_DCHECK(!waiting_);
1181 ScopedSetTrue s(&waiting_);
Markus Handell9a21c492022-08-25 11:40:13 +00001182 const int cmsWait = ToCmsWait(max_wait_duration);
jbauchde4db112017-05-31 13:09:18 -07001183#if defined(WEBRTC_USE_EPOLL)
1184 // We don't keep a dedicated "epoll" descriptor containing only the non-IO
1185 // (i.e. signaling) dispatcher, so "poll" will be used instead of the default
1186 // "select" to support sockets larger than FD_SETSIZE.
1187 if (!process_io) {
1188 return WaitPoll(cmsWait, signal_wakeup_);
1189 } else if (epoll_fd_ != INVALID_SOCKET) {
1190 return WaitEpoll(cmsWait);
1191 }
1192#endif
1193 return WaitSelect(cmsWait, process_io);
1194}
1195
Taylor Brandstetter3041eb22021-11-02 19:46:40 +00001196// `error_event` is true if we are responding to an event where we know an
1197// error has occurred, which is possible with the poll/epoll implementations
1198// but not the select implementation.
1199//
1200// `check_error` is true if there is the possibility of an error.
jbauchde4db112017-05-31 13:09:18 -07001201static void ProcessEvents(Dispatcher* dispatcher,
1202 bool readable,
1203 bool writable,
Taylor Brandstetter3041eb22021-11-02 19:46:40 +00001204 bool error_event,
jbauchde4db112017-05-31 13:09:18 -07001205 bool check_error) {
Taylor Brandstetter3041eb22021-11-02 19:46:40 +00001206 RTC_DCHECK(!(error_event && !check_error));
jbauchde4db112017-05-31 13:09:18 -07001207 int errcode = 0;
jbauchde4db112017-05-31 13:09:18 -07001208 if (check_error) {
1209 socklen_t len = sizeof(errcode);
Taylor Brandstetter3041eb22021-11-02 19:46:40 +00001210 int res = ::getsockopt(dispatcher->GetDescriptor(), SOL_SOCKET, SO_ERROR,
1211 &errcode, &len);
1212 if (res < 0) {
1213 // If we are sure an error has occurred, or if getsockopt failed for a
1214 // socket descriptor, make sure we set the error code to a nonzero value.
1215 if (error_event || errno != ENOTSOCK) {
1216 errcode = EBADF;
1217 }
1218 }
jbauchde4db112017-05-31 13:09:18 -07001219 }
1220
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001221 // Most often the socket is writable or readable or both, so make a single
1222 // virtual call to get requested events
1223 const uint32_t requested_events = dispatcher->GetRequestedEvents();
jbauchde4db112017-05-31 13:09:18 -07001224 uint32_t ff = 0;
1225
1226 // Check readable descriptors. If we're waiting on an accept, signal
1227 // that. Otherwise we're waiting for data, check to see if we're
1228 // readable or really closed.
1229 // TODO(pthatcher): Only peek at TCP descriptors.
1230 if (readable) {
Taylor Brandstetter3041eb22021-11-02 19:46:40 +00001231 if (errcode || dispatcher->IsDescriptorClosed()) {
jbauchde4db112017-05-31 13:09:18 -07001232 ff |= DE_CLOSE;
Taylor Brandstetter3041eb22021-11-02 19:46:40 +00001233 } else if (requested_events & DE_ACCEPT) {
1234 ff |= DE_ACCEPT;
jbauchde4db112017-05-31 13:09:18 -07001235 } else {
1236 ff |= DE_READ;
1237 }
1238 }
1239
1240 // Check writable descriptors. If we're waiting on a connect, detect
1241 // success versus failure by the reaped error code.
1242 if (writable) {
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001243 if (requested_events & DE_CONNECT) {
jbauchde4db112017-05-31 13:09:18 -07001244 if (!errcode) {
1245 ff |= DE_CONNECT;
jbauchde4db112017-05-31 13:09:18 -07001246 }
1247 } else {
1248 ff |= DE_WRITE;
1249 }
1250 }
1251
Taylor Brandstetter3041eb22021-11-02 19:46:40 +00001252 // Make sure we report any errors regardless of whether readable or writable.
1253 if (errcode) {
1254 ff |= DE_CLOSE;
1255 }
1256
jbauchde4db112017-05-31 13:09:18 -07001257 // Tell the descriptor about the event.
1258 if (ff != 0) {
jbauchde4db112017-05-31 13:09:18 -07001259 dispatcher->OnEvent(ff, errcode);
1260 }
1261}
1262
1263bool PhysicalSocketServer::WaitSelect(int cmsWait, bool process_io) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001264 // Calculate timing information
1265
deadbeef37f5ecf2017-02-27 14:06:41 -08001266 struct timeval* ptvWait = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001267 struct timeval tvWait;
Niels Möller689b5872018-08-29 09:55:44 +02001268 int64_t stop_us;
Markus Handell9a21c492022-08-25 11:40:13 +00001269 if (cmsWait != kForeverMs) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001270 // Calculate wait timeval
1271 tvWait.tv_sec = cmsWait / 1000;
1272 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1273 ptvWait = &tvWait;
1274
Niels Möller689b5872018-08-29 09:55:44 +02001275 // Calculate when to return
1276 stop_us = rtc::TimeMicros() + cmsWait * 1000;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001277 }
1278
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001279 fd_set fdsRead;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001280 fd_set fdsWrite;
Yves Gerey665174f2018-06-19 15:03:05 +02001281// Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1282// inline assembly in FD_ZERO.
1283// http://crbug.com/344505
pbos@webrtc.org27e58982014-10-07 17:56:53 +00001284#ifdef MEMORY_SANITIZER
1285 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1286 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1287#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001288
1289 fWait_ = true;
1290
1291 while (fWait_) {
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001292 // Zero all fd_sets. Although select() zeros the descriptors not signaled,
1293 // we may need to do this for dispatchers that were deleted while
1294 // iterating.
1295 FD_ZERO(&fdsRead);
1296 FD_ZERO(&fdsWrite);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001297 int fdmax = -1;
1298 {
1299 CritScope cr(&crit_);
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001300 current_dispatcher_keys_.clear();
1301 for (auto const& kv : dispatcher_by_key_) {
1302 uint64_t key = kv.first;
1303 Dispatcher* pdispatcher = kv.second;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001304 // Query dispatchers for read and write wait state
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001305 if (!process_io && (pdispatcher != signal_wakeup_))
1306 continue;
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001307 current_dispatcher_keys_.push_back(key);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001308 int fd = pdispatcher->GetDescriptor();
jbauchde4db112017-05-31 13:09:18 -07001309 // "select"ing a file descriptor that is equal to or larger than
1310 // FD_SETSIZE will result in undefined behavior.
1311 RTC_DCHECK_LT(fd, FD_SETSIZE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001312 if (fd > fdmax)
1313 fdmax = fd;
1314
Peter Boström0c4e06b2015-10-07 12:23:21 +02001315 uint32_t ff = pdispatcher->GetRequestedEvents();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001316 if (ff & (DE_READ | DE_ACCEPT))
1317 FD_SET(fd, &fdsRead);
1318 if (ff & (DE_WRITE | DE_CONNECT))
1319 FD_SET(fd, &fdsWrite);
1320 }
1321 }
1322
1323 // Wait then call handlers as appropriate
1324 // < 0 means error
1325 // 0 means timeout
1326 // > 0 means count of descriptors ready
deadbeef37f5ecf2017-02-27 14:06:41 -08001327 int n = select(fdmax + 1, &fdsRead, &fdsWrite, nullptr, ptvWait);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001328
1329 // If error, return error.
1330 if (n < 0) {
1331 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001332 RTC_LOG_E(LS_ERROR, EN, errno) << "select";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001333 return false;
1334 }
1335 // Else ignore the error and keep going. If this EINTR was for one of the
1336 // signals managed by this PhysicalSocketServer, the
1337 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1338 // iteration.
1339 } else if (n == 0) {
1340 // If timeout, return success
1341 return true;
1342 } else {
1343 // We have signaled descriptors
1344 CritScope cr(&crit_);
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001345 // Iterate only on the dispatchers whose sockets were passed into
1346 // WSAEventSelect; this avoids the ABA problem (a socket being
1347 // destroyed and a new one created with the same file descriptor).
1348 for (uint64_t key : current_dispatcher_keys_) {
1349 if (!dispatcher_by_key_.count(key))
1350 continue;
1351 Dispatcher* pdispatcher = dispatcher_by_key_.at(key);
1352
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001353 int fd = pdispatcher->GetDescriptor();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001354
jbauchde4db112017-05-31 13:09:18 -07001355 bool readable = FD_ISSET(fd, &fdsRead);
1356 if (readable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001357 FD_CLR(fd, &fdsRead);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001358 }
1359
jbauchde4db112017-05-31 13:09:18 -07001360 bool writable = FD_ISSET(fd, &fdsWrite);
1361 if (writable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001362 FD_CLR(fd, &fdsWrite);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001363 }
1364
jbauchde4db112017-05-31 13:09:18 -07001365 // The error code can be signaled through reads or writes.
Taylor Brandstetter3041eb22021-11-02 19:46:40 +00001366 ProcessEvents(pdispatcher, readable, writable, /*error_event=*/false,
1367 readable || writable);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001368 }
1369 }
1370
1371 // Recalc the time remaining to wait. Doing it here means it doesn't get
1372 // calced twice the first time through the loop
1373 if (ptvWait) {
1374 ptvWait->tv_sec = 0;
1375 ptvWait->tv_usec = 0;
Niels Möller689b5872018-08-29 09:55:44 +02001376 int64_t time_left_us = stop_us - rtc::TimeMicros();
1377 if (time_left_us > 0) {
1378 ptvWait->tv_sec = time_left_us / rtc::kNumMicrosecsPerSec;
1379 ptvWait->tv_usec = time_left_us % rtc::kNumMicrosecsPerSec;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001380 }
1381 }
1382 }
1383
1384 return true;
1385}
1386
jbauchde4db112017-05-31 13:09:18 -07001387#if defined(WEBRTC_USE_EPOLL)
1388
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001389void PhysicalSocketServer::AddEpoll(Dispatcher* pdispatcher, uint64_t key) {
jbauchde4db112017-05-31 13:09:18 -07001390 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 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
Taylor Brandstetter3041eb22021-11-02 19:46:40 +00001399 if (event.events == 0u) {
1400 // Don't add at all if we don't have any requested events. Could indicate a
1401 // closed socket.
1402 return;
1403 }
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001404 event.data.u64 = key;
jbauchde4db112017-05-31 13:09:18 -07001405 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &event);
1406 RTC_DCHECK_EQ(err, 0);
1407 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001408 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_ADD";
jbauchde4db112017-05-31 13:09:18 -07001409 }
1410}
1411
1412void PhysicalSocketServer::RemoveEpoll(Dispatcher* pdispatcher) {
1413 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1414 int fd = pdispatcher->GetDescriptor();
1415 RTC_DCHECK(fd != INVALID_SOCKET);
1416 if (fd == INVALID_SOCKET) {
1417 return;
1418 }
1419
1420 struct epoll_event event = {0};
1421 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &event);
1422 RTC_DCHECK(err == 0 || errno == ENOENT);
Taylor Brandstetter3041eb22021-11-02 19:46:40 +00001423 // Ignore ENOENT, which could occur if this descriptor wasn't added due to
1424 // having no requested events.
1425 if (err == -1 && errno != ENOENT) {
1426 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001427 }
1428}
1429
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001430void PhysicalSocketServer::UpdateEpoll(Dispatcher* pdispatcher, uint64_t key) {
jbauchde4db112017-05-31 13:09:18 -07001431 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1432 int fd = pdispatcher->GetDescriptor();
1433 RTC_DCHECK(fd != INVALID_SOCKET);
1434 if (fd == INVALID_SOCKET) {
1435 return;
1436 }
1437
1438 struct epoll_event event = {0};
1439 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001440 event.data.u64 = key;
Taylor Brandstetter3041eb22021-11-02 19:46:40 +00001441 // Remove if we don't have any requested events. Could indicate a closed
1442 // socket.
1443 if (event.events == 0u) {
1444 epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &event);
1445 } else {
1446 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &event);
1447 RTC_DCHECK(err == 0 || errno == ENOENT);
1448 if (err == -1) {
1449 // Could have been removed earlier due to no requested events.
1450 if (errno == ENOENT) {
1451 err = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &event);
1452 if (err == -1) {
1453 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_ADD";
1454 }
1455 } else {
1456 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_MOD";
1457 }
1458 }
jbauchde4db112017-05-31 13:09:18 -07001459 }
1460}
1461
1462bool PhysicalSocketServer::WaitEpoll(int cmsWait) {
1463 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1464 int64_t tvWait = -1;
1465 int64_t tvStop = -1;
Markus Handell9a21c492022-08-25 11:40:13 +00001466 if (cmsWait != kForeverMs) {
jbauchde4db112017-05-31 13:09:18 -07001467 tvWait = cmsWait;
1468 tvStop = TimeAfter(cmsWait);
1469 }
1470
jbauchde4db112017-05-31 13:09:18 -07001471 fWait_ = true;
jbauchde4db112017-05-31 13:09:18 -07001472 while (fWait_) {
1473 // Wait then call handlers as appropriate
1474 // < 0 means error
1475 // 0 means timeout
1476 // > 0 means count of descriptors ready
Markus Handellb7c63ab2020-05-26 18:09:55 +02001477 int n = epoll_wait(epoll_fd_, epoll_events_.data(), epoll_events_.size(),
jbauchde4db112017-05-31 13:09:18 -07001478 static_cast<int>(tvWait));
1479 if (n < 0) {
1480 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001481 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll";
jbauchde4db112017-05-31 13:09:18 -07001482 return false;
1483 }
1484 // Else ignore the error and keep going. If this EINTR was for one of the
1485 // signals managed by this PhysicalSocketServer, the
1486 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1487 // iteration.
1488 } else if (n == 0) {
1489 // If timeout, return success
1490 return true;
1491 } else {
1492 // We have signaled descriptors
1493 CritScope cr(&crit_);
1494 for (int i = 0; i < n; ++i) {
1495 const epoll_event& event = epoll_events_[i];
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001496 uint64_t key = event.data.u64;
1497 if (!dispatcher_by_key_.count(key)) {
jbauchde4db112017-05-31 13:09:18 -07001498 // The dispatcher for this socket no longer exists.
1499 continue;
1500 }
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001501 Dispatcher* pdispatcher = dispatcher_by_key_.at(key);
jbauchde4db112017-05-31 13:09:18 -07001502
1503 bool readable = (event.events & (EPOLLIN | EPOLLPRI));
1504 bool writable = (event.events & EPOLLOUT);
Taylor Brandstetter3041eb22021-11-02 19:46:40 +00001505 bool error = (event.events & (EPOLLRDHUP | EPOLLERR | EPOLLHUP));
jbauchde4db112017-05-31 13:09:18 -07001506
Taylor Brandstetter3041eb22021-11-02 19:46:40 +00001507 ProcessEvents(pdispatcher, readable, writable, error, error);
jbauchde4db112017-05-31 13:09:18 -07001508 }
1509 }
1510
Markus Handell9a21c492022-08-25 11:40:13 +00001511 if (cmsWait != kForeverMs) {
jbauchde4db112017-05-31 13:09:18 -07001512 tvWait = TimeDiff(tvStop, TimeMillis());
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001513 if (tvWait <= 0) {
jbauchde4db112017-05-31 13:09:18 -07001514 // Return success on timeout.
1515 return true;
1516 }
1517 }
1518 }
1519
1520 return true;
1521}
1522
1523bool PhysicalSocketServer::WaitPoll(int cmsWait, Dispatcher* dispatcher) {
1524 RTC_DCHECK(dispatcher);
1525 int64_t tvWait = -1;
1526 int64_t tvStop = -1;
Markus Handell9a21c492022-08-25 11:40:13 +00001527 if (cmsWait != kForeverMs) {
jbauchde4db112017-05-31 13:09:18 -07001528 tvWait = cmsWait;
1529 tvStop = TimeAfter(cmsWait);
1530 }
1531
1532 fWait_ = true;
1533
1534 struct pollfd fds = {0};
1535 int fd = dispatcher->GetDescriptor();
1536 fds.fd = fd;
1537
1538 while (fWait_) {
1539 uint32_t ff = dispatcher->GetRequestedEvents();
1540 fds.events = 0;
1541 if (ff & (DE_READ | DE_ACCEPT)) {
1542 fds.events |= POLLIN;
1543 }
1544 if (ff & (DE_WRITE | DE_CONNECT)) {
1545 fds.events |= POLLOUT;
1546 }
1547 fds.revents = 0;
1548
1549 // Wait then call handlers as appropriate
1550 // < 0 means error
1551 // 0 means timeout
1552 // > 0 means count of descriptors ready
1553 int n = poll(&fds, 1, static_cast<int>(tvWait));
1554 if (n < 0) {
1555 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001556 RTC_LOG_E(LS_ERROR, EN, errno) << "poll";
jbauchde4db112017-05-31 13:09:18 -07001557 return false;
1558 }
1559 // Else ignore the error and keep going. If this EINTR was for one of the
1560 // signals managed by this PhysicalSocketServer, the
1561 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1562 // iteration.
1563 } else if (n == 0) {
1564 // If timeout, return success
1565 return true;
1566 } else {
1567 // We have signaled descriptors (should only be the passed dispatcher).
1568 RTC_DCHECK_EQ(n, 1);
1569 RTC_DCHECK_EQ(fds.fd, fd);
1570
1571 bool readable = (fds.revents & (POLLIN | POLLPRI));
1572 bool writable = (fds.revents & POLLOUT);
Taylor Brandstetter3041eb22021-11-02 19:46:40 +00001573 bool error = (fds.revents & (POLLRDHUP | POLLERR | POLLHUP));
jbauchde4db112017-05-31 13:09:18 -07001574
Taylor Brandstetter3041eb22021-11-02 19:46:40 +00001575 ProcessEvents(dispatcher, readable, writable, error, error);
jbauchde4db112017-05-31 13:09:18 -07001576 }
1577
Markus Handell9a21c492022-08-25 11:40:13 +00001578 if (cmsWait != kForeverMs) {
jbauchde4db112017-05-31 13:09:18 -07001579 tvWait = TimeDiff(tvStop, TimeMillis());
1580 if (tvWait < 0) {
1581 // Return success on timeout.
1582 return true;
1583 }
1584 }
1585 }
1586
1587 return true;
1588}
1589
1590#endif // WEBRTC_USE_EPOLL
1591
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001592#endif // WEBRTC_POSIX
1593
1594#if defined(WEBRTC_WIN)
Markus Handell9a21c492022-08-25 11:40:13 +00001595bool PhysicalSocketServer::Wait(webrtc::TimeDelta max_wait_duration,
1596 bool process_io) {
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001597 // We don't support reentrant waiting.
1598 RTC_DCHECK(!waiting_);
1599 ScopedSetTrue s(&waiting_);
1600
Markus Handell9a21c492022-08-25 11:40:13 +00001601 int cmsWait = ToCmsWait(max_wait_duration);
Honghai Zhang82d78622016-05-06 11:29:15 -07001602 int64_t cmsTotal = cmsWait;
1603 int64_t cmsElapsed = 0;
1604 int64_t msStart = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001605
1606 fWait_ = true;
1607 while (fWait_) {
1608 std::vector<WSAEVENT> events;
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001609 std::vector<uint64_t> event_owners;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001610
1611 events.push_back(socket_ev_);
1612
1613 {
1614 CritScope cr(&crit_);
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001615 // Get a snapshot of all current dispatchers; this is used to avoid the
1616 // ABA problem (see later comment) and avoids the dispatcher_by_key_
1617 // iterator being invalidated by calling CheckSignalClose, which may
1618 // remove the dispatcher from the list.
1619 current_dispatcher_keys_.clear();
1620 for (auto const& kv : dispatcher_by_key_) {
1621 current_dispatcher_keys_.push_back(kv.first);
1622 }
1623 for (uint64_t key : current_dispatcher_keys_) {
1624 if (!dispatcher_by_key_.count(key)) {
1625 continue;
1626 }
1627 Dispatcher* disp = dispatcher_by_key_.at(key);
1628 if (!disp)
1629 continue;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001630 if (!process_io && (disp != signal_wakeup_))
1631 continue;
1632 SOCKET s = disp->GetSocket();
1633 if (disp->CheckSignalClose()) {
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001634 // We just signalled close, don't poll this socket.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001635 } else if (s != INVALID_SOCKET) {
Yves Gerey665174f2018-06-19 15:03:05 +02001636 WSAEventSelect(s, events[0],
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001637 FlagsToEvents(disp->GetRequestedEvents()));
1638 } else {
1639 events.push_back(disp->GetWSAEvent());
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001640 event_owners.push_back(key);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001641 }
1642 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001643 }
1644
1645 // Which is shorter, the delay wait or the asked wait?
1646
Honghai Zhang82d78622016-05-06 11:29:15 -07001647 int64_t cmsNext;
Markus Handell9a21c492022-08-25 11:40:13 +00001648 if (cmsWait == kForeverMs) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001649 cmsNext = cmsWait;
1650 } else {
Honghai Zhang82d78622016-05-06 11:29:15 -07001651 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001652 }
1653
1654 // Wait for one of the events to signal
Yves Gerey665174f2018-06-19 15:03:05 +02001655 DWORD dw =
1656 WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()), &events[0],
1657 false, static_cast<DWORD>(cmsNext), false);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001658
1659 if (dw == WSA_WAIT_FAILED) {
1660 // Failed?
jbauch095ae152015-12-18 01:39:55 -08001661 // TODO(pthatcher): need a better strategy than this!
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001662 WSAGetLastError();
Artem Titovd3251962021-11-15 16:57:07 +01001663 RTC_DCHECK_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001664 return false;
1665 } else if (dw == WSA_WAIT_TIMEOUT) {
1666 // Timeout?
1667 return true;
1668 } else {
1669 // Figure out which one it is and call it
1670 CritScope cr(&crit_);
1671 int index = dw - WSA_WAIT_EVENT_0;
1672 if (index > 0) {
Yves Gerey665174f2018-06-19 15:03:05 +02001673 --index; // The first event is the socket event
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001674 uint64_t key = event_owners[index];
1675 if (!dispatcher_by_key_.count(key)) {
1676 // The dispatcher could have been removed while waiting for events.
1677 continue;
jbauchde4db112017-05-31 13:09:18 -07001678 }
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001679 Dispatcher* disp = dispatcher_by_key_.at(key);
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001680 disp->OnEvent(0, 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001681 } else if (process_io) {
Taylor Brandstetter7b69a442020-08-20 23:43:13 +00001682 // Iterate only on the dispatchers whose sockets were passed into
1683 // WSAEventSelect; this avoids the ABA problem (a socket being
1684 // destroyed and a new one created with the same SOCKET handle).
1685 for (uint64_t key : current_dispatcher_keys_) {
1686 if (!dispatcher_by_key_.count(key)) {
1687 continue;
1688 }
1689 Dispatcher* disp = dispatcher_by_key_.at(key);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001690 SOCKET s = disp->GetSocket();
1691 if (s == INVALID_SOCKET)
1692 continue;
1693
1694 WSANETWORKEVENTS wsaEvents;
1695 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1696 if (err == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001697 {
1698 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1699 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
Harald Alvestrandef5b21e2021-11-27 21:31:08 +00001700 RTC_LOG(LS_WARNING)
Mirko Bonadei675513b2017-11-09 11:09:25 +01001701 << "PhysicalSocketServer got FD_READ_BIT error "
1702 << wsaEvents.iErrorCode[FD_READ_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001703 }
1704 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1705 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
Harald Alvestrandef5b21e2021-11-27 21:31:08 +00001706 RTC_LOG(LS_WARNING)
Mirko Bonadei675513b2017-11-09 11:09:25 +01001707 << "PhysicalSocketServer got FD_WRITE_BIT error "
1708 << wsaEvents.iErrorCode[FD_WRITE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001709 }
1710 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1711 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
Harald Alvestrandef5b21e2021-11-27 21:31:08 +00001712 RTC_LOG(LS_WARNING)
Mirko Bonadei675513b2017-11-09 11:09:25 +01001713 << "PhysicalSocketServer got FD_CONNECT_BIT error "
1714 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001715 }
1716 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1717 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
Harald Alvestrandef5b21e2021-11-27 21:31:08 +00001718 RTC_LOG(LS_WARNING)
Mirko Bonadei675513b2017-11-09 11:09:25 +01001719 << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1720 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001721 }
1722 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1723 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
Harald Alvestrandef5b21e2021-11-27 21:31:08 +00001724 RTC_LOG(LS_WARNING)
Mirko Bonadei675513b2017-11-09 11:09:25 +01001725 << "PhysicalSocketServer got FD_CLOSE_BIT error "
1726 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001727 }
1728 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001729 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001730 int errcode = 0;
1731 if (wsaEvents.lNetworkEvents & FD_READ)
1732 ff |= DE_READ;
1733 if (wsaEvents.lNetworkEvents & FD_WRITE)
1734 ff |= DE_WRITE;
1735 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1736 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1737 ff |= DE_CONNECT;
1738 } else {
1739 ff |= DE_CLOSE;
1740 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1741 }
1742 }
1743 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1744 ff |= DE_ACCEPT;
1745 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1746 ff |= DE_CLOSE;
1747 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1748 }
1749 if (ff != 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001750 disp->OnEvent(ff, errcode);
1751 }
1752 }
1753 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001754 }
1755
1756 // Reset the network event until new activity occurs
1757 WSAResetEvent(socket_ev_);
1758 }
1759
1760 // Break?
1761 if (!fWait_)
1762 break;
1763 cmsElapsed = TimeSince(msStart);
Markus Handell9a21c492022-08-25 11:40:13 +00001764 if ((cmsWait != kForeverMs) && (cmsElapsed >= cmsWait)) {
Yves Gerey665174f2018-06-19 15:03:05 +02001765 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001766 }
1767 }
1768
1769 // Done
1770 return true;
1771}
honghaizcec0a082016-01-15 14:49:09 -08001772#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001773
1774} // namespace rtc