blob: 080534af2c7d05849b7e95c0a00f2586a41f5048 [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
Mirko Bonadeiff88a642020-05-13 13:48:11 +000027#include <signal.h>
Yves Gerey665174f2018-06-19 15:03:05 +020028#include <sys/ioctl.h>
29#include <sys/select.h>
30#include <sys/time.h>
31#include <unistd.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000032#endif
33
34#if defined(WEBRTC_WIN)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000035#include <windows.h>
36#include <winsock2.h>
37#include <ws2tcpip.h>
38#undef SetPort
39#endif
40
Patrik Höglunda8005cf2017-12-13 16:05:42 +010041#include <errno.h>
42
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000043#include <algorithm>
44#include <map>
45
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020046#include "rtc_base/arraysize.h"
Steve Anton10542f22019-01-11 09:11:00 -080047#include "rtc_base/byte_order.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "rtc_base/checks.h"
49#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080050#include "rtc_base/network_monitor.h"
51#include "rtc_base/null_socket_server.h"
52#include "rtc_base/time_utils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000053
Emilio Cobos Álvarez68065502019-05-29 15:30:32 +020054#if defined(WEBRTC_LINUX)
55#include <linux/sockios.h>
56#endif
57
Patrik Höglunda8005cf2017-12-13 16:05:42 +010058#if defined(WEBRTC_WIN)
59#define LAST_SYSTEM_ERROR (::GetLastError())
60#elif defined(__native_client__) && __native_client__
61#define LAST_SYSTEM_ERROR (0)
62#elif defined(WEBRTC_POSIX)
63#define LAST_SYSTEM_ERROR (errno)
64#endif // WEBRTC_WIN
65
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000066#if defined(WEBRTC_POSIX)
67#include <netinet/tcp.h> // for TCP_NODELAY
Yves Gerey665174f2018-06-19 15:03:05 +020068#define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000069typedef void* SockOptArg;
Stefan Holmer9131efd2016-05-23 18:19:26 +020070
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000071#endif // WEBRTC_POSIX
72
Stefan Holmer3ebb3ef2016-05-23 20:26:11 +020073#if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) && !defined(__native_client__)
74
Stefan Holmer9131efd2016-05-23 18:19:26 +020075int64_t GetSocketRecvTimestamp(int socket) {
76 struct timeval tv_ioctl;
77 int ret = ioctl(socket, SIOCGSTAMP, &tv_ioctl);
78 if (ret != 0)
79 return -1;
80 int64_t timestamp =
81 rtc::kNumMicrosecsPerSec * static_cast<int64_t>(tv_ioctl.tv_sec) +
82 static_cast<int64_t>(tv_ioctl.tv_usec);
83 return timestamp;
84}
85
86#else
87
88int64_t GetSocketRecvTimestamp(int socket) {
89 return -1;
90}
91#endif
92
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000093#if defined(WEBRTC_WIN)
94typedef char* SockOptArg;
95#endif
96
jbauchde4db112017-05-31 13:09:18 -070097#if defined(WEBRTC_USE_EPOLL)
98// POLLRDHUP / EPOLLRDHUP are only defined starting with Linux 2.6.17.
99#if !defined(POLLRDHUP)
100#define POLLRDHUP 0x2000
101#endif
102#if !defined(EPOLLRDHUP)
103#define EPOLLRDHUP 0x2000
104#endif
105#endif
106
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000107namespace rtc {
108
danilchapbebf54c2016-04-28 01:32:48 -0700109std::unique_ptr<SocketServer> SocketServer::CreateDefault() {
110#if defined(__native_client__)
111 return std::unique_ptr<SocketServer>(new rtc::NullSocketServer);
112#else
113 return std::unique_ptr<SocketServer>(new rtc::PhysicalSocketServer);
114#endif
115}
116
jbauch095ae152015-12-18 01:39:55 -0800117PhysicalSocket::PhysicalSocket(PhysicalSocketServer* ss, SOCKET s)
Yves Gerey665174f2018-06-19 15:03:05 +0200118 : ss_(ss),
119 s_(s),
120 error_(0),
121 state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED),
122 resolver_(nullptr) {
jbauch095ae152015-12-18 01:39:55 -0800123 if (s_ != INVALID_SOCKET) {
jbauch577f5dc2017-05-17 16:32:26 -0700124 SetEnabledEvents(DE_READ | DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000125
jbauch095ae152015-12-18 01:39:55 -0800126 int type = SOCK_STREAM;
127 socklen_t len = sizeof(type);
nissec16fa5e2017-02-07 07:18:43 -0800128 const int res =
129 getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len);
130 RTC_DCHECK_EQ(0, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000131 udp_ = (SOCK_DGRAM == type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000132 }
jbauch095ae152015-12-18 01:39:55 -0800133}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000134
jbauch095ae152015-12-18 01:39:55 -0800135PhysicalSocket::~PhysicalSocket() {
136 Close();
137}
138
139bool PhysicalSocket::Create(int family, int type) {
140 Close();
141 s_ = ::socket(family, type, 0);
142 udp_ = (SOCK_DGRAM == type);
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800143 family_ = family;
jbauch095ae152015-12-18 01:39:55 -0800144 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700145 if (udp_) {
146 SetEnabledEvents(DE_READ | DE_WRITE);
147 }
jbauch095ae152015-12-18 01:39:55 -0800148 return s_ != INVALID_SOCKET;
149}
150
151SocketAddress PhysicalSocket::GetLocalAddress() const {
Mirko Bonadei108a2f02019-11-20 19:43:38 +0100152 sockaddr_storage addr_storage = {};
jbauch095ae152015-12-18 01:39:55 -0800153 socklen_t addrlen = sizeof(addr_storage);
154 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
155 int result = ::getsockname(s_, addr, &addrlen);
156 SocketAddress address;
157 if (result >= 0) {
158 SocketAddressFromSockAddrStorage(addr_storage, &address);
159 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100160 RTC_LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
161 << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000162 }
jbauch095ae152015-12-18 01:39:55 -0800163 return address;
164}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000165
jbauch095ae152015-12-18 01:39:55 -0800166SocketAddress PhysicalSocket::GetRemoteAddress() const {
Mirko Bonadei108a2f02019-11-20 19:43:38 +0100167 sockaddr_storage addr_storage = {};
jbauch095ae152015-12-18 01:39:55 -0800168 socklen_t addrlen = sizeof(addr_storage);
169 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
170 int result = ::getpeername(s_, addr, &addrlen);
171 SocketAddress address;
172 if (result >= 0) {
173 SocketAddressFromSockAddrStorage(addr_storage, &address);
174 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100175 RTC_LOG(LS_WARNING)
176 << "GetRemoteAddress: unable to get remote addr, socket=" << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000177 }
jbauch095ae152015-12-18 01:39:55 -0800178 return address;
179}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000180
jbauch095ae152015-12-18 01:39:55 -0800181int PhysicalSocket::Bind(const SocketAddress& bind_addr) {
deadbeefc874d122017-02-13 15:41:59 -0800182 SocketAddress copied_bind_addr = bind_addr;
183 // If a network binder is available, use it to bind a socket to an interface
184 // instead of bind(), since this is more reliable on an OS with a weak host
185 // model.
deadbeef9ffa13f2017-02-21 16:18:00 -0800186 if (ss_->network_binder() && !bind_addr.IsAnyIP()) {
deadbeefc874d122017-02-13 15:41:59 -0800187 NetworkBindingResult result =
188 ss_->network_binder()->BindSocketToNetwork(s_, bind_addr.ipaddr());
189 if (result == NetworkBindingResult::SUCCESS) {
190 // Since the network binder handled binding the socket to the desired
191 // network interface, we don't need to (and shouldn't) include an IP in
192 // the bind() call; bind() just needs to assign a port.
193 copied_bind_addr.SetIP(GetAnyIP(copied_bind_addr.ipaddr().family()));
194 } else if (result == NetworkBindingResult::NOT_IMPLEMENTED) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100195 RTC_LOG(LS_INFO) << "Can't bind socket to network because "
196 "network binding is not implemented for this OS.";
deadbeefc874d122017-02-13 15:41:59 -0800197 } else {
198 if (bind_addr.IsLoopbackIP()) {
199 // If we couldn't bind to a loopback IP (which should only happen in
200 // test scenarios), continue on. This may be expected behavior.
Paulina Hensmanb239a2e2020-03-31 16:16:11 +0200201 RTC_LOG(LS_VERBOSE) << "Binding socket to loopback address"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100202 << " failed; result: " << static_cast<int>(result);
deadbeefc874d122017-02-13 15:41:59 -0800203 } else {
Paulina Hensmanb239a2e2020-03-31 16:16:11 +0200204 RTC_LOG(LS_WARNING) << "Binding socket to network address"
Mirko Bonadei675513b2017-11-09 11:09:25 +0100205 << " failed; result: " << static_cast<int>(result);
deadbeefc874d122017-02-13 15:41:59 -0800206 // If a network binding was attempted and failed, we should stop here
207 // and not try to use the socket. Otherwise, we may end up sending
208 // packets with an invalid source address.
209 // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=7026
210 return -1;
211 }
212 }
213 }
jbauch095ae152015-12-18 01:39:55 -0800214 sockaddr_storage addr_storage;
deadbeefc874d122017-02-13 15:41:59 -0800215 size_t len = copied_bind_addr.ToSockAddrStorage(&addr_storage);
jbauch095ae152015-12-18 01:39:55 -0800216 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
217 int err = ::bind(s_, addr, static_cast<int>(len));
218 UpdateLastError();
tfarinaa41ab932015-10-30 16:08:48 -0700219#if !defined(NDEBUG)
jbauch095ae152015-12-18 01:39:55 -0800220 if (0 == err) {
221 dbg_addr_ = "Bound @ ";
222 dbg_addr_.append(GetLocalAddress().ToString());
223 }
tfarinaa41ab932015-10-30 16:08:48 -0700224#endif
jbauch095ae152015-12-18 01:39:55 -0800225 return err;
226}
227
228int PhysicalSocket::Connect(const SocketAddress& addr) {
229 // TODO(pthatcher): Implicit creation is required to reconnect...
230 // ...but should we make it more explicit?
231 if (state_ != CS_CLOSED) {
232 SetError(EALREADY);
233 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000234 }
jbauch095ae152015-12-18 01:39:55 -0800235 if (addr.IsUnresolvedIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100236 RTC_LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
jbauch095ae152015-12-18 01:39:55 -0800237 resolver_ = new AsyncResolver();
238 resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult);
239 resolver_->Start(addr);
240 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000241 return 0;
242 }
243
jbauch095ae152015-12-18 01:39:55 -0800244 return DoConnect(addr);
245}
246
247int PhysicalSocket::DoConnect(const SocketAddress& connect_addr) {
Yves Gerey665174f2018-06-19 15:03:05 +0200248 if ((s_ == INVALID_SOCKET) && !Create(connect_addr.family(), SOCK_STREAM)) {
jbauch095ae152015-12-18 01:39:55 -0800249 return SOCKET_ERROR;
250 }
251 sockaddr_storage addr_storage;
252 size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
253 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
254 int err = ::connect(s_, addr, static_cast<int>(len));
255 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700256 uint8_t events = DE_READ | DE_WRITE;
jbauch095ae152015-12-18 01:39:55 -0800257 if (err == 0) {
258 state_ = CS_CONNECTED;
259 } else if (IsBlockingError(GetError())) {
260 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700261 events |= DE_CONNECT;
jbauch095ae152015-12-18 01:39:55 -0800262 } else {
263 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000264 }
265
jbauch577f5dc2017-05-17 16:32:26 -0700266 EnableEvents(events);
jbauch095ae152015-12-18 01:39:55 -0800267 return 0;
268}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000269
jbauch095ae152015-12-18 01:39:55 -0800270int PhysicalSocket::GetError() const {
271 CritScope cs(&crit_);
272 return error_;
273}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000274
jbauch095ae152015-12-18 01:39:55 -0800275void PhysicalSocket::SetError(int error) {
276 CritScope cs(&crit_);
277 error_ = error;
278}
279
280AsyncSocket::ConnState PhysicalSocket::GetState() const {
281 return state_;
282}
283
284int PhysicalSocket::GetOption(Option opt, int* value) {
285 int slevel;
286 int sopt;
287 if (TranslateOption(opt, &slevel, &sopt) == -1)
288 return -1;
289 socklen_t optlen = sizeof(*value);
290 int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800291 if (ret == -1) {
292 return -1;
293 }
294 if (opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000295#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800296 *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000297#endif
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800298 } else if (opt == OPT_DSCP) {
299#if defined(WEBRTC_POSIX)
300 // unshift DSCP value to get six most significant bits of IP DiffServ field
301 *value >>= 2;
302#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000303 }
jbauch095ae152015-12-18 01:39:55 -0800304 return ret;
305}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000306
jbauch095ae152015-12-18 01:39:55 -0800307int PhysicalSocket::SetOption(Option opt, int value) {
308 int slevel;
309 int sopt;
310 if (TranslateOption(opt, &slevel, &sopt) == -1)
311 return -1;
312 if (opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000313#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800314 value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000315#endif
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800316 } else if (opt == OPT_DSCP) {
317#if defined(WEBRTC_POSIX)
318 // shift DSCP value to fit six most significant bits of IP DiffServ field
319 value <<= 2;
320#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000321 }
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800322#if defined(WEBRTC_POSIX)
323 if (sopt == IPV6_TCLASS) {
324 // Set the IPv4 option in all cases to support dual-stack sockets.
325 ::setsockopt(s_, IPPROTO_IP, IP_TOS, (SockOptArg)&value, sizeof(value));
326 }
327#endif
jbauch095ae152015-12-18 01:39:55 -0800328 return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
329}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000330
jbauch095ae152015-12-18 01:39:55 -0800331int PhysicalSocket::Send(const void* pv, size_t cb) {
Yves Gerey665174f2018-06-19 15:03:05 +0200332 int sent = DoSend(
333 s_, reinterpret_cast<const char*>(pv), static_cast<int>(cb),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000334#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800335 // Suppress SIGPIPE. Without this, attempting to send on a socket whose
336 // other end is closed will result in a SIGPIPE signal being raised to
337 // our process, which by default will terminate the process, which we
338 // don't want. By specifying this flag, we'll just get the error EPIPE
339 // instead and can handle the error gracefully.
340 MSG_NOSIGNAL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000341#else
jbauch095ae152015-12-18 01:39:55 -0800342 0
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000343#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200344 );
jbauch095ae152015-12-18 01:39:55 -0800345 UpdateLastError();
346 MaybeRemapSendError();
347 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800348 RTC_DCHECK(sent <= static_cast<int>(cb));
jbauchf2a2bf42016-02-03 16:45:32 -0800349 if ((sent > 0 && sent < static_cast<int>(cb)) ||
350 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700351 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000352 }
jbauch095ae152015-12-18 01:39:55 -0800353 return sent;
354}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000355
jbauch095ae152015-12-18 01:39:55 -0800356int PhysicalSocket::SendTo(const void* buffer,
357 size_t length,
358 const SocketAddress& addr) {
359 sockaddr_storage saddr;
360 size_t len = addr.ToSockAddrStorage(&saddr);
Yves Gerey665174f2018-06-19 15:03:05 +0200361 int sent =
362 DoSendTo(s_, static_cast<const char*>(buffer), static_cast<int>(length),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000363#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
Yves Gerey665174f2018-06-19 15:03:05 +0200364 // Suppress SIGPIPE. See above for explanation.
365 MSG_NOSIGNAL,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000366#else
Yves Gerey665174f2018-06-19 15:03:05 +0200367 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000368#endif
Yves Gerey665174f2018-06-19 15:03:05 +0200369 reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
jbauch095ae152015-12-18 01:39:55 -0800370 UpdateLastError();
371 MaybeRemapSendError();
372 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800373 RTC_DCHECK(sent <= static_cast<int>(length));
jbauchf2a2bf42016-02-03 16:45:32 -0800374 if ((sent > 0 && sent < static_cast<int>(length)) ||
375 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700376 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000377 }
jbauch095ae152015-12-18 01:39:55 -0800378 return sent;
379}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000380
Stefan Holmer9131efd2016-05-23 18:19:26 +0200381int PhysicalSocket::Recv(void* buffer, size_t length, int64_t* timestamp) {
Yves Gerey665174f2018-06-19 15:03:05 +0200382 int received =
383 ::recv(s_, static_cast<char*>(buffer), static_cast<int>(length), 0);
jbauch095ae152015-12-18 01:39:55 -0800384 if ((received == 0) && (length != 0)) {
385 // Note: on graceful shutdown, recv can return 0. In this case, we
386 // pretend it is blocking, and then signal close, so that simplifying
387 // assumptions can be made about Recv.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100388 RTC_LOG(LS_WARNING) << "EOF from socket; deferring close event";
jbauch095ae152015-12-18 01:39:55 -0800389 // Must turn this back on so that the select() loop will notice the close
390 // event.
jbauch577f5dc2017-05-17 16:32:26 -0700391 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800392 SetError(EWOULDBLOCK);
393 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000394 }
Stefan Holmer9131efd2016-05-23 18:19:26 +0200395 if (timestamp) {
396 *timestamp = GetSocketRecvTimestamp(s_);
397 }
jbauch095ae152015-12-18 01:39:55 -0800398 UpdateLastError();
399 int error = GetError();
400 bool success = (received >= 0) || IsBlockingError(error);
401 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700402 EnableEvents(DE_READ);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000403 }
jbauch095ae152015-12-18 01:39:55 -0800404 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100405 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000406 }
jbauch095ae152015-12-18 01:39:55 -0800407 return received;
408}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000409
jbauch095ae152015-12-18 01:39:55 -0800410int PhysicalSocket::RecvFrom(void* buffer,
411 size_t length,
Stefan Holmer9131efd2016-05-23 18:19:26 +0200412 SocketAddress* out_addr,
413 int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800414 sockaddr_storage addr_storage;
415 socklen_t addr_len = sizeof(addr_storage);
416 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
417 int received = ::recvfrom(s_, static_cast<char*>(buffer),
418 static_cast<int>(length), 0, addr, &addr_len);
Stefan Holmer9131efd2016-05-23 18:19:26 +0200419 if (timestamp) {
420 *timestamp = GetSocketRecvTimestamp(s_);
421 }
jbauch095ae152015-12-18 01:39:55 -0800422 UpdateLastError();
423 if ((received >= 0) && (out_addr != nullptr))
424 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
425 int error = GetError();
426 bool success = (received >= 0) || IsBlockingError(error);
427 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700428 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800429 }
430 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100431 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
jbauch095ae152015-12-18 01:39:55 -0800432 }
433 return received;
434}
435
436int PhysicalSocket::Listen(int backlog) {
437 int err = ::listen(s_, backlog);
438 UpdateLastError();
439 if (err == 0) {
440 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700441 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800442#if !defined(NDEBUG)
443 dbg_addr_ = "Listening @ ";
444 dbg_addr_.append(GetLocalAddress().ToString());
445#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000446 }
jbauch095ae152015-12-18 01:39:55 -0800447 return err;
448}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000449
jbauch095ae152015-12-18 01:39:55 -0800450AsyncSocket* PhysicalSocket::Accept(SocketAddress* out_addr) {
451 // Always re-subscribe DE_ACCEPT to make sure new incoming connections will
452 // trigger an event even if DoAccept returns an error here.
jbauch577f5dc2017-05-17 16:32:26 -0700453 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800454 sockaddr_storage addr_storage;
455 socklen_t addr_len = sizeof(addr_storage);
456 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
457 SOCKET s = DoAccept(s_, addr, &addr_len);
458 UpdateLastError();
459 if (s == INVALID_SOCKET)
460 return nullptr;
461 if (out_addr != nullptr)
462 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
463 return ss_->WrapSocket(s);
464}
465
466int PhysicalSocket::Close() {
467 if (s_ == INVALID_SOCKET)
468 return 0;
469 int err = ::closesocket(s_);
470 UpdateLastError();
471 s_ = INVALID_SOCKET;
472 state_ = CS_CLOSED;
jbauch577f5dc2017-05-17 16:32:26 -0700473 SetEnabledEvents(0);
jbauch095ae152015-12-18 01:39:55 -0800474 if (resolver_) {
475 resolver_->Destroy(false);
476 resolver_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000477 }
jbauch095ae152015-12-18 01:39:55 -0800478 return err;
479}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000480
jbauch095ae152015-12-18 01:39:55 -0800481SOCKET PhysicalSocket::DoAccept(SOCKET socket,
482 sockaddr* addr,
483 socklen_t* addrlen) {
484 return ::accept(socket, addr, addrlen);
485}
486
jbauchf2a2bf42016-02-03 16:45:32 -0800487int PhysicalSocket::DoSend(SOCKET socket, const char* buf, int len, int flags) {
488 return ::send(socket, buf, len, flags);
489}
490
491int PhysicalSocket::DoSendTo(SOCKET socket,
492 const char* buf,
493 int len,
494 int flags,
495 const struct sockaddr* dest_addr,
496 socklen_t addrlen) {
497 return ::sendto(socket, buf, len, flags, dest_addr, addrlen);
498}
499
jbauch095ae152015-12-18 01:39:55 -0800500void PhysicalSocket::OnResolveResult(AsyncResolverInterface* resolver) {
501 if (resolver != resolver_) {
502 return;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000503 }
504
jbauch095ae152015-12-18 01:39:55 -0800505 int error = resolver_->GetError();
506 if (error == 0) {
507 error = DoConnect(resolver_->address());
508 } else {
509 Close();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000510 }
511
jbauch095ae152015-12-18 01:39:55 -0800512 if (error) {
513 SetError(error);
514 SignalCloseEvent(this, error);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000515 }
jbauch095ae152015-12-18 01:39:55 -0800516}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000517
jbauch095ae152015-12-18 01:39:55 -0800518void PhysicalSocket::UpdateLastError() {
Patrik Höglunda8005cf2017-12-13 16:05:42 +0100519 SetError(LAST_SYSTEM_ERROR);
jbauch095ae152015-12-18 01:39:55 -0800520}
521
522void PhysicalSocket::MaybeRemapSendError() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000523#if defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800524 // https://developer.apple.com/library/mac/documentation/Darwin/
525 // Reference/ManPages/man2/sendto.2.html
526 // ENOBUFS - The output queue for a network interface is full.
527 // This generally indicates that the interface has stopped sending,
528 // but may be caused by transient congestion.
529 if (GetError() == ENOBUFS) {
530 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000531 }
jbauch095ae152015-12-18 01:39:55 -0800532#endif
533}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000534
jbauch577f5dc2017-05-17 16:32:26 -0700535void PhysicalSocket::SetEnabledEvents(uint8_t events) {
536 enabled_events_ = events;
537}
538
539void PhysicalSocket::EnableEvents(uint8_t events) {
540 enabled_events_ |= events;
541}
542
543void PhysicalSocket::DisableEvents(uint8_t events) {
544 enabled_events_ &= ~events;
545}
546
jbauch095ae152015-12-18 01:39:55 -0800547int PhysicalSocket::TranslateOption(Option opt, int* slevel, int* sopt) {
548 switch (opt) {
549 case OPT_DONTFRAGMENT:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000550#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800551 *slevel = IPPROTO_IP;
552 *sopt = IP_DONTFRAGMENT;
553 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000554#elif defined(WEBRTC_MAC) || defined(BSD) || defined(__native_client__)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100555 RTC_LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
jbauch095ae152015-12-18 01:39:55 -0800556 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000557#elif defined(WEBRTC_POSIX)
jbauch095ae152015-12-18 01:39:55 -0800558 *slevel = IPPROTO_IP;
559 *sopt = IP_MTU_DISCOVER;
560 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000561#endif
jbauch095ae152015-12-18 01:39:55 -0800562 case OPT_RCVBUF:
563 *slevel = SOL_SOCKET;
564 *sopt = SO_RCVBUF;
565 break;
566 case OPT_SNDBUF:
567 *slevel = SOL_SOCKET;
568 *sopt = SO_SNDBUF;
569 break;
570 case OPT_NODELAY:
571 *slevel = IPPROTO_TCP;
572 *sopt = TCP_NODELAY;
573 break;
574 case OPT_DSCP:
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800575#if defined(WEBRTC_POSIX)
576 if (family_ == AF_INET6) {
577 *slevel = IPPROTO_IPV6;
578 *sopt = IPV6_TCLASS;
579 } else {
580 *slevel = IPPROTO_IP;
581 *sopt = IP_TOS;
582 }
583 break;
584#else
Mirko Bonadei675513b2017-11-09 11:09:25 +0100585 RTC_LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
jbauch095ae152015-12-18 01:39:55 -0800586 return -1;
Taylor Brandstetterecd6fc82020-02-05 17:26:37 -0800587#endif
jbauch095ae152015-12-18 01:39:55 -0800588 case OPT_RTP_SENDTIME_EXTN_ID:
589 return -1; // No logging is necessary as this not a OS socket option.
590 default:
nissec80e7412017-01-11 05:56:46 -0800591 RTC_NOTREACHED();
jbauch095ae152015-12-18 01:39:55 -0800592 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000593 }
jbauch095ae152015-12-18 01:39:55 -0800594 return 0;
595}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000596
Yves Gerey665174f2018-06-19 15:03:05 +0200597SocketDispatcher::SocketDispatcher(PhysicalSocketServer* ss)
jbauch4331fcd2016-01-06 22:20:28 -0800598#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200599 : PhysicalSocket(ss),
600 id_(0),
601 signal_close_(false)
jbauch4331fcd2016-01-06 22:20:28 -0800602#else
Yves Gerey665174f2018-06-19 15:03:05 +0200603 : PhysicalSocket(ss)
jbauch4331fcd2016-01-06 22:20:28 -0800604#endif
605{
606}
607
Yves Gerey665174f2018-06-19 15:03:05 +0200608SocketDispatcher::SocketDispatcher(SOCKET s, PhysicalSocketServer* ss)
jbauch4331fcd2016-01-06 22:20:28 -0800609#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200610 : PhysicalSocket(ss, s),
611 id_(0),
612 signal_close_(false)
jbauch4331fcd2016-01-06 22:20:28 -0800613#else
Yves Gerey665174f2018-06-19 15:03:05 +0200614 : PhysicalSocket(ss, s)
jbauch4331fcd2016-01-06 22:20:28 -0800615#endif
616{
617}
618
619SocketDispatcher::~SocketDispatcher() {
620 Close();
621}
622
623bool SocketDispatcher::Initialize() {
nisseede5da42017-01-12 05:15:36 -0800624 RTC_DCHECK(s_ != INVALID_SOCKET);
Yves Gerey665174f2018-06-19 15:03:05 +0200625// Must be a non-blocking
jbauch4331fcd2016-01-06 22:20:28 -0800626#if defined(WEBRTC_WIN)
627 u_long argp = 1;
628 ioctlsocket(s_, FIONBIO, &argp);
629#elif defined(WEBRTC_POSIX)
630 fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
631#endif
deadbeefeae45642017-05-26 16:27:09 -0700632#if defined(WEBRTC_IOS)
633 // iOS may kill sockets when the app is moved to the background
634 // (specifically, if the app doesn't use the "voip" UIBackgroundMode). When
635 // we attempt to write to such a socket, SIGPIPE will be raised, which by
636 // default will terminate the process, which we don't want. By specifying
637 // this socket option, SIGPIPE will be disabled for the socket.
638 int value = 1;
639 ::setsockopt(s_, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value));
640#endif
jbauch4331fcd2016-01-06 22:20:28 -0800641 ss_->Add(this);
642 return true;
643}
644
645bool SocketDispatcher::Create(int type) {
646 return Create(AF_INET, type);
647}
648
649bool SocketDispatcher::Create(int family, int type) {
650 // Change the socket to be non-blocking.
651 if (!PhysicalSocket::Create(family, type))
652 return false;
653
654 if (!Initialize())
655 return false;
656
657#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200658 do {
659 id_ = ++next_id_;
660 } while (id_ == 0);
jbauch4331fcd2016-01-06 22:20:28 -0800661#endif
662 return true;
663}
664
665#if defined(WEBRTC_WIN)
666
667WSAEVENT SocketDispatcher::GetWSAEvent() {
668 return WSA_INVALID_EVENT;
669}
670
671SOCKET SocketDispatcher::GetSocket() {
672 return s_;
673}
674
675bool SocketDispatcher::CheckSignalClose() {
676 if (!signal_close_)
677 return false;
678
679 char ch;
680 if (recv(s_, &ch, 1, MSG_PEEK) > 0)
681 return false;
682
683 state_ = CS_CLOSED;
684 signal_close_ = false;
685 SignalCloseEvent(this, signal_err_);
686 return true;
687}
688
689int SocketDispatcher::next_id_ = 0;
690
691#elif defined(WEBRTC_POSIX)
692
693int SocketDispatcher::GetDescriptor() {
694 return s_;
695}
696
697bool SocketDispatcher::IsDescriptorClosed() {
deadbeeffaedf7f2017-02-09 15:09:22 -0800698 if (udp_) {
699 // The MSG_PEEK trick doesn't work for UDP, since (at least in some
700 // circumstances) it requires reading an entire UDP packet, which would be
701 // bad for performance here. So, just check whether |s_| has been closed,
702 // which should be sufficient.
703 return s_ == INVALID_SOCKET;
704 }
jbauch4331fcd2016-01-06 22:20:28 -0800705 // We don't have a reliable way of distinguishing end-of-stream
706 // from readability. So test on each readable call. Is this
707 // inefficient? Probably.
708 char ch;
709 ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
710 if (res > 0) {
711 // Data available, so not closed.
712 return false;
713 } else if (res == 0) {
714 // EOF, so closed.
715 return true;
716 } else { // error
717 switch (errno) {
718 // Returned if we've already closed s_.
719 case EBADF:
720 // Returned during ungraceful peer shutdown.
721 case ECONNRESET:
722 return true;
deadbeeffaedf7f2017-02-09 15:09:22 -0800723 // The normal blocking error; don't log anything.
724 case EWOULDBLOCK:
725 // Interrupted system call.
726 case EINTR:
727 return false;
jbauch4331fcd2016-01-06 22:20:28 -0800728 default:
729 // Assume that all other errors are just blocking errors, meaning the
730 // connection is still good but we just can't read from it right now.
731 // This should only happen when connecting (and at most once), because
732 // in all other cases this function is only called if the file
733 // descriptor is already known to be in the readable state. However,
734 // it's not necessary a problem if we spuriously interpret a
735 // "connection lost"-type error as a blocking error, because typically
736 // the next recv() will get EOF, so we'll still eventually notice that
737 // the socket is closed.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100738 RTC_LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
jbauch4331fcd2016-01-06 22:20:28 -0800739 return false;
740 }
741 }
742}
743
Yves Gerey665174f2018-06-19 15:03:05 +0200744#endif // WEBRTC_POSIX
jbauch4331fcd2016-01-06 22:20:28 -0800745
746uint32_t SocketDispatcher::GetRequestedEvents() {
jbauch577f5dc2017-05-17 16:32:26 -0700747 return enabled_events();
jbauch4331fcd2016-01-06 22:20:28 -0800748}
749
750void SocketDispatcher::OnPreEvent(uint32_t ff) {
751 if ((ff & DE_CONNECT) != 0)
752 state_ = CS_CONNECTED;
753
754#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200755// We set CS_CLOSED from CheckSignalClose.
jbauch4331fcd2016-01-06 22:20:28 -0800756#elif defined(WEBRTC_POSIX)
757 if ((ff & DE_CLOSE) != 0)
758 state_ = CS_CLOSED;
759#endif
760}
761
762#if defined(WEBRTC_WIN)
763
764void SocketDispatcher::OnEvent(uint32_t ff, int err) {
765 int cache_id = id_;
766 // Make sure we deliver connect/accept first. Otherwise, consumers may see
767 // something like a READ followed by a CONNECT, which would be odd.
768 if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
769 if (ff != DE_CONNECT)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100770 RTC_LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
jbauch577f5dc2017-05-17 16:32:26 -0700771 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800772#if !defined(NDEBUG)
773 dbg_addr_ = "Connected @ ";
774 dbg_addr_.append(GetRemoteAddress().ToString());
775#endif
776 SignalConnectEvent(this);
777 }
778 if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700779 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800780 SignalReadEvent(this);
781 }
782 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700783 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800784 SignalReadEvent(this);
785 }
786 if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700787 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800788 SignalWriteEvent(this);
789 }
790 if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
791 signal_close_ = true;
792 signal_err_ = err;
793 }
794}
795
796#elif defined(WEBRTC_POSIX)
797
798void SocketDispatcher::OnEvent(uint32_t ff, int err) {
jbauchde4db112017-05-31 13:09:18 -0700799#if defined(WEBRTC_USE_EPOLL)
800 // Remember currently enabled events so we can combine multiple changes
801 // into one update call later.
802 // The signal handlers might re-enable events disabled here, so we can't
803 // keep a list of events to disable at the end of the method. This list
804 // would not be updated with the events enabled by the signal handlers.
805 StartBatchedEventUpdates();
806#endif
jbauch4331fcd2016-01-06 22:20:28 -0800807 // Make sure we deliver connect/accept first. Otherwise, consumers may see
808 // something like a READ followed by a CONNECT, which would be odd.
809 if ((ff & DE_CONNECT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700810 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800811 SignalConnectEvent(this);
812 }
813 if ((ff & DE_ACCEPT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700814 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800815 SignalReadEvent(this);
816 }
817 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700818 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800819 SignalReadEvent(this);
820 }
821 if ((ff & DE_WRITE) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700822 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800823 SignalWriteEvent(this);
824 }
825 if ((ff & DE_CLOSE) != 0) {
826 // The socket is now dead to us, so stop checking it.
jbauch577f5dc2017-05-17 16:32:26 -0700827 SetEnabledEvents(0);
jbauch4331fcd2016-01-06 22:20:28 -0800828 SignalCloseEvent(this, err);
829 }
jbauchde4db112017-05-31 13:09:18 -0700830#if defined(WEBRTC_USE_EPOLL)
831 FinishBatchedEventUpdates();
832#endif
jbauch4331fcd2016-01-06 22:20:28 -0800833}
834
Yves Gerey665174f2018-06-19 15:03:05 +0200835#endif // WEBRTC_POSIX
jbauch4331fcd2016-01-06 22:20:28 -0800836
jbauchde4db112017-05-31 13:09:18 -0700837#if defined(WEBRTC_USE_EPOLL)
838
839static int GetEpollEvents(uint32_t ff) {
840 int events = 0;
841 if (ff & (DE_READ | DE_ACCEPT)) {
842 events |= EPOLLIN;
843 }
844 if (ff & (DE_WRITE | DE_CONNECT)) {
845 events |= EPOLLOUT;
846 }
847 return events;
848}
849
850void SocketDispatcher::StartBatchedEventUpdates() {
851 RTC_DCHECK_EQ(saved_enabled_events_, -1);
852 saved_enabled_events_ = enabled_events();
853}
854
855void SocketDispatcher::FinishBatchedEventUpdates() {
856 RTC_DCHECK_NE(saved_enabled_events_, -1);
857 uint8_t old_events = static_cast<uint8_t>(saved_enabled_events_);
858 saved_enabled_events_ = -1;
859 MaybeUpdateDispatcher(old_events);
860}
861
862void SocketDispatcher::MaybeUpdateDispatcher(uint8_t old_events) {
863 if (GetEpollEvents(enabled_events()) != GetEpollEvents(old_events) &&
864 saved_enabled_events_ == -1) {
865 ss_->Update(this);
866 }
867}
868
869void SocketDispatcher::SetEnabledEvents(uint8_t events) {
870 uint8_t old_events = enabled_events();
871 PhysicalSocket::SetEnabledEvents(events);
872 MaybeUpdateDispatcher(old_events);
873}
874
875void SocketDispatcher::EnableEvents(uint8_t events) {
876 uint8_t old_events = enabled_events();
877 PhysicalSocket::EnableEvents(events);
878 MaybeUpdateDispatcher(old_events);
879}
880
881void SocketDispatcher::DisableEvents(uint8_t events) {
882 uint8_t old_events = enabled_events();
883 PhysicalSocket::DisableEvents(events);
884 MaybeUpdateDispatcher(old_events);
885}
886
887#endif // WEBRTC_USE_EPOLL
888
jbauch4331fcd2016-01-06 22:20:28 -0800889int SocketDispatcher::Close() {
890 if (s_ == INVALID_SOCKET)
891 return 0;
892
893#if defined(WEBRTC_WIN)
894 id_ = 0;
895 signal_close_ = false;
896#endif
mmorrison25eeda12020-04-07 16:13:13 -0600897#if defined(WEBRTC_USE_EPOLL)
898 // If we're batching events, the socket can be closed and reopened
899 // during the batch. Set saved_enabled_events_ to 0 here so the new
900 // socket, if any, has the correct old events bitfield
901 if (saved_enabled_events_ != -1) {
902 saved_enabled_events_ = 0;
903 }
904#endif
jbauch4331fcd2016-01-06 22:20:28 -0800905 ss_->Remove(this);
906 return PhysicalSocket::Close();
907}
908
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000909#if defined(WEBRTC_POSIX)
910class EventDispatcher : public Dispatcher {
911 public:
912 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
913 if (pipe(afd_) < 0)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100914 RTC_LOG(LERROR) << "pipe failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000915 ss_->Add(this);
916 }
917
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000918 ~EventDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000919 ss_->Remove(this);
920 close(afd_[0]);
921 close(afd_[1]);
922 }
923
924 virtual void Signal() {
925 CritScope cs(&crit_);
926 if (!fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200927 const uint8_t b[1] = {0};
nissec16fa5e2017-02-07 07:18:43 -0800928 const ssize_t res = write(afd_[1], b, sizeof(b));
929 RTC_DCHECK_EQ(1, res);
930 fSignaled_ = true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000931 }
932 }
933
Peter Boström0c4e06b2015-10-07 12:23:21 +0200934 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000935
Peter Boström0c4e06b2015-10-07 12:23:21 +0200936 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000937 // It is not possible to perfectly emulate an auto-resetting event with
938 // pipes. This simulates it by resetting before the event is handled.
939
940 CritScope cs(&crit_);
941 if (fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200942 uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
nissec16fa5e2017-02-07 07:18:43 -0800943 const ssize_t res = read(afd_[0], b, sizeof(b));
944 RTC_DCHECK_EQ(1, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000945 fSignaled_ = false;
946 }
947 }
948
nissec80e7412017-01-11 05:56:46 -0800949 void OnEvent(uint32_t ff, int err) override { RTC_NOTREACHED(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000950
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000951 int GetDescriptor() override { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000952
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000953 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000954
955 private:
Yves Gerey665174f2018-06-19 15:03:05 +0200956 PhysicalSocketServer* ss_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000957 int afd_[2];
958 bool fSignaled_;
959 CriticalSection crit_;
960};
961
Mirko Bonadeiff88a642020-05-13 13:48:11 +0000962// These two classes use the self-pipe trick to deliver POSIX signals to our
963// select loop. This is the only safe, reliable, cross-platform way to do
964// non-trivial things with a POSIX signal in an event-driven program (until
965// proper pselect() implementations become ubiquitous).
966
967class PosixSignalHandler {
968 public:
969 // POSIX only specifies 32 signals, but in principle the system might have
970 // more and the programmer might choose to use them, so we size our array
971 // for 128.
972 static constexpr int kNumPosixSignals = 128;
973
974 // There is just a single global instance. (Signal handlers do not get any
975 // sort of user-defined void * parameter, so they can't access anything that
976 // isn't global.)
977 static PosixSignalHandler* Instance() {
978 static PosixSignalHandler* const instance = new PosixSignalHandler();
979 return instance;
980 }
981
982 // Returns true if the given signal number is set.
983 bool IsSignalSet(int signum) const {
984 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
985 if (signum < static_cast<int>(arraysize(received_signal_))) {
986 return received_signal_[signum];
987 } else {
988 return false;
989 }
990 }
991
992 // Clears the given signal number.
993 void ClearSignal(int signum) {
994 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
995 if (signum < static_cast<int>(arraysize(received_signal_))) {
996 received_signal_[signum] = false;
997 }
998 }
999
1000 // Returns the file descriptor to monitor for signal events.
1001 int GetDescriptor() const { return afd_[0]; }
1002
1003 // This is called directly from our real signal handler, so it must be
1004 // signal-handler-safe. That means it cannot assume anything about the
1005 // user-level state of the process, since the handler could be executed at any
1006 // time on any thread.
1007 void OnPosixSignalReceived(int signum) {
1008 if (signum >= static_cast<int>(arraysize(received_signal_))) {
1009 // We don't have space in our array for this.
1010 return;
1011 }
1012 // Set a flag saying we've seen this signal.
1013 received_signal_[signum] = true;
1014 // Notify application code that we got a signal.
1015 const uint8_t b[1] = {0};
1016 if (-1 == write(afd_[1], b, sizeof(b))) {
1017 // Nothing we can do here. If there's an error somehow then there's
1018 // nothing we can safely do from a signal handler.
1019 // No, we can't even safely log it.
1020 // But, we still have to check the return value here. Otherwise,
1021 // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
1022 return;
1023 }
1024 }
1025
1026 private:
1027 PosixSignalHandler() {
1028 if (pipe(afd_) < 0) {
1029 RTC_LOG_ERR(LS_ERROR) << "pipe failed";
1030 return;
1031 }
1032 if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
1033 RTC_LOG_ERR(LS_WARNING) << "fcntl #1 failed";
1034 }
1035 if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
1036 RTC_LOG_ERR(LS_WARNING) << "fcntl #2 failed";
1037 }
1038 memset(const_cast<void*>(static_cast<volatile void*>(received_signal_)), 0,
1039 sizeof(received_signal_));
1040 }
1041
1042 ~PosixSignalHandler() {
1043 int fd1 = afd_[0];
1044 int fd2 = afd_[1];
1045 // We clobber the stored file descriptor numbers here or else in principle
1046 // a signal that happens to be delivered during application termination
1047 // could erroneously write a zero byte to an unrelated file handle in
1048 // OnPosixSignalReceived() if some other file happens to be opened later
1049 // during shutdown and happens to be given the same file descriptor number
1050 // as our pipe had. Unfortunately even with this precaution there is still a
1051 // race where that could occur if said signal happens to be handled
1052 // concurrently with this code and happens to have already read the value of
1053 // afd_[1] from memory before we clobber it, but that's unlikely.
1054 afd_[0] = -1;
1055 afd_[1] = -1;
1056 close(fd1);
1057 close(fd2);
1058 }
1059
1060 int afd_[2];
1061 // These are boolean flags that will be set in our signal handler and read
1062 // and cleared from Wait(). There is a race involved in this, but it is
1063 // benign. The signal handler sets the flag before signaling the pipe, so
1064 // we'll never end up blocking in select() while a flag is still true.
1065 // However, if two of the same signal arrive close to each other then it's
1066 // possible that the second time the handler may set the flag while it's still
1067 // true, meaning that signal will be missed. But the first occurrence of it
1068 // will still be handled, so this isn't a problem.
1069 // Volatile is not necessary here for correctness, but this data _is_ volatile
1070 // so I've marked it as such.
1071 volatile uint8_t received_signal_[kNumPosixSignals];
1072};
1073
1074class PosixSignalDispatcher : public Dispatcher {
1075 public:
1076 PosixSignalDispatcher(PhysicalSocketServer* owner) : owner_(owner) {
1077 owner_->Add(this);
1078 }
1079
1080 ~PosixSignalDispatcher() override { owner_->Remove(this); }
1081
1082 uint32_t GetRequestedEvents() override { return DE_READ; }
1083
1084 void OnPreEvent(uint32_t ff) override {
1085 // Events might get grouped if signals come very fast, so we read out up to
1086 // 16 bytes to make sure we keep the pipe empty.
1087 uint8_t b[16];
1088 ssize_t ret = read(GetDescriptor(), b, sizeof(b));
1089 if (ret < 0) {
1090 RTC_LOG_ERR(LS_WARNING) << "Error in read()";
1091 } else if (ret == 0) {
1092 RTC_LOG(LS_WARNING) << "Should have read at least one byte";
1093 }
1094 }
1095
1096 void OnEvent(uint32_t ff, int err) override {
1097 for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
1098 ++signum) {
1099 if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
1100 PosixSignalHandler::Instance()->ClearSignal(signum);
1101 HandlerMap::iterator i = handlers_.find(signum);
1102 if (i == handlers_.end()) {
1103 // This can happen if a signal is delivered to our process at around
1104 // the same time as we unset our handler for it. It is not an error
1105 // condition, but it's unusual enough to be worth logging.
1106 RTC_LOG(LS_INFO) << "Received signal with no handler: " << signum;
1107 } else {
1108 // Otherwise, execute our handler.
1109 (*i->second)(signum);
1110 }
1111 }
1112 }
1113 }
1114
1115 int GetDescriptor() override {
1116 return PosixSignalHandler::Instance()->GetDescriptor();
1117 }
1118
1119 bool IsDescriptorClosed() override { return false; }
1120
1121 void SetHandler(int signum, void (*handler)(int)) {
1122 handlers_[signum] = handler;
1123 }
1124
1125 void ClearHandler(int signum) { handlers_.erase(signum); }
1126
1127 bool HasHandlers() { return !handlers_.empty(); }
1128
1129 private:
1130 typedef std::map<int, void (*)(int)> HandlerMap;
1131
1132 HandlerMap handlers_;
1133 // Our owner.
1134 PhysicalSocketServer* owner_;
1135};
1136
Yves Gerey665174f2018-06-19 15:03:05 +02001137#endif // WEBRTC_POSIX
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001138
1139#if defined(WEBRTC_WIN)
Peter Boström0c4e06b2015-10-07 12:23:21 +02001140static uint32_t FlagsToEvents(uint32_t events) {
1141 uint32_t ffFD = FD_CLOSE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001142 if (events & DE_READ)
1143 ffFD |= FD_READ;
1144 if (events & DE_WRITE)
1145 ffFD |= FD_WRITE;
1146 if (events & DE_CONNECT)
1147 ffFD |= FD_CONNECT;
1148 if (events & DE_ACCEPT)
1149 ffFD |= FD_ACCEPT;
1150 return ffFD;
1151}
1152
1153class EventDispatcher : public Dispatcher {
1154 public:
Yves Gerey665174f2018-06-19 15:03:05 +02001155 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001156 hev_ = WSACreateEvent();
1157 if (hev_) {
1158 ss_->Add(this);
1159 }
1160 }
1161
Steve Anton9de3aac2017-10-24 10:08:26 -07001162 ~EventDispatcher() override {
deadbeef37f5ecf2017-02-27 14:06:41 -08001163 if (hev_ != nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001164 ss_->Remove(this);
1165 WSACloseEvent(hev_);
deadbeef37f5ecf2017-02-27 14:06:41 -08001166 hev_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001167 }
1168 }
1169
1170 virtual void Signal() {
deadbeef37f5ecf2017-02-27 14:06:41 -08001171 if (hev_ != nullptr)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001172 WSASetEvent(hev_);
1173 }
1174
Steve Anton9de3aac2017-10-24 10:08:26 -07001175 uint32_t GetRequestedEvents() override { return 0; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001176
Steve Anton9de3aac2017-10-24 10:08:26 -07001177 void OnPreEvent(uint32_t ff) override { WSAResetEvent(hev_); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001178
Steve Anton9de3aac2017-10-24 10:08:26 -07001179 void OnEvent(uint32_t ff, int err) override {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001180
Steve Anton9de3aac2017-10-24 10:08:26 -07001181 WSAEVENT GetWSAEvent() override { return hev_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001182
Steve Anton9de3aac2017-10-24 10:08:26 -07001183 SOCKET GetSocket() override { return INVALID_SOCKET; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001184
Steve Anton9de3aac2017-10-24 10:08:26 -07001185 bool CheckSignalClose() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001186
Steve Anton9de3aac2017-10-24 10:08:26 -07001187 private:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001188 PhysicalSocketServer* ss_;
1189 WSAEVENT hev_;
1190};
honghaizcec0a082016-01-15 14:49:09 -08001191#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001192
1193// Sets the value of a boolean value to false when signaled.
1194class Signaler : public EventDispatcher {
1195 public:
Yves Gerey665174f2018-06-19 15:03:05 +02001196 Signaler(PhysicalSocketServer* ss, bool* pf) : EventDispatcher(ss), pf_(pf) {}
1197 ~Signaler() override {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001198
Peter Boström0c4e06b2015-10-07 12:23:21 +02001199 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001200 if (pf_)
1201 *pf_ = false;
1202 }
1203
1204 private:
Yves Gerey665174f2018-06-19 15:03:05 +02001205 bool* pf_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001206};
1207
Yves Gerey665174f2018-06-19 15:03:05 +02001208PhysicalSocketServer::PhysicalSocketServer() : fWait_(false) {
jbauchde4db112017-05-31 13:09:18 -07001209#if defined(WEBRTC_USE_EPOLL)
1210 // Since Linux 2.6.8, the size argument is ignored, but must be greater than
1211 // zero. Before that the size served as hint to the kernel for the amount of
1212 // space to initially allocate in internal data structures.
1213 epoll_fd_ = epoll_create(FD_SETSIZE);
1214 if (epoll_fd_ == -1) {
1215 // Not an error, will fall back to "select" below.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001216 RTC_LOG_E(LS_WARNING, EN, errno) << "epoll_create";
jbauchde4db112017-05-31 13:09:18 -07001217 epoll_fd_ = INVALID_SOCKET;
1218 }
1219#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001220 signal_wakeup_ = new Signaler(this, &fWait_);
1221#if defined(WEBRTC_WIN)
1222 socket_ev_ = WSACreateEvent();
1223#endif
1224}
1225
1226PhysicalSocketServer::~PhysicalSocketServer() {
1227#if defined(WEBRTC_WIN)
1228 WSACloseEvent(socket_ev_);
1229#endif
Mirko Bonadeiff88a642020-05-13 13:48:11 +00001230#if defined(WEBRTC_POSIX)
1231 signal_dispatcher_.reset();
1232#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001233 delete signal_wakeup_;
jbauchde4db112017-05-31 13:09:18 -07001234#if defined(WEBRTC_USE_EPOLL)
1235 if (epoll_fd_ != INVALID_SOCKET) {
1236 close(epoll_fd_);
1237 }
1238#endif
nisseede5da42017-01-12 05:15:36 -08001239 RTC_DCHECK(dispatchers_.empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001240}
1241
1242void PhysicalSocketServer::WakeUp() {
1243 signal_wakeup_->Signal();
1244}
1245
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001246Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
1247 PhysicalSocket* socket = new PhysicalSocket(this);
1248 if (socket->Create(family, type)) {
1249 return socket;
1250 } else {
1251 delete socket;
jbauch095ae152015-12-18 01:39:55 -08001252 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001253 }
1254}
1255
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001256AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
1257 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1258 if (dispatcher->Create(family, type)) {
1259 return dispatcher;
1260 } else {
1261 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001262 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001263 }
1264}
1265
1266AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
1267 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1268 if (dispatcher->Initialize()) {
1269 return dispatcher;
1270 } else {
1271 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001272 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001273 }
1274}
1275
Yves Gerey665174f2018-06-19 15:03:05 +02001276void PhysicalSocketServer::Add(Dispatcher* pdispatcher) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001277 CritScope cs(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001278 if (processing_dispatchers_) {
1279 // A dispatcher is being added while a "Wait" call is processing the
1280 // list of socket events.
1281 // Defer adding to "dispatchers_" set until processing is done to avoid
1282 // invalidating the iterator in "Wait".
1283 pending_remove_dispatchers_.erase(pdispatcher);
1284 pending_add_dispatchers_.insert(pdispatcher);
1285 } else {
1286 dispatchers_.insert(pdispatcher);
1287 }
1288#if defined(WEBRTC_USE_EPOLL)
1289 if (epoll_fd_ != INVALID_SOCKET) {
1290 AddEpoll(pdispatcher);
1291 }
1292#endif // WEBRTC_USE_EPOLL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001293}
1294
Yves Gerey665174f2018-06-19 15:03:05 +02001295void PhysicalSocketServer::Remove(Dispatcher* pdispatcher) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001296 CritScope cs(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001297 if (processing_dispatchers_) {
1298 // A dispatcher is being removed while a "Wait" call is processing the
1299 // list of socket events.
1300 // Defer removal from "dispatchers_" set until processing is done to avoid
1301 // invalidating the iterator in "Wait".
1302 if (!pending_add_dispatchers_.erase(pdispatcher) &&
1303 dispatchers_.find(pdispatcher) == dispatchers_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001304 RTC_LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
Jonas Olssonb2b20312020-01-14 12:11:31 +01001305 "dispatcher, potentially from a duplicate call to "
1306 "Add.";
jbauchde4db112017-05-31 13:09:18 -07001307 return;
1308 }
1309
1310 pending_remove_dispatchers_.insert(pdispatcher);
1311 } else if (!dispatchers_.erase(pdispatcher)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001312 RTC_LOG(LS_WARNING)
1313 << "PhysicalSocketServer asked to remove a unknown "
Jonas Olssonb2b20312020-01-14 12:11:31 +01001314 "dispatcher, potentially from a duplicate call to Add.";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001315 return;
1316 }
jbauchde4db112017-05-31 13:09:18 -07001317#if defined(WEBRTC_USE_EPOLL)
1318 if (epoll_fd_ != INVALID_SOCKET) {
1319 RemoveEpoll(pdispatcher);
1320 }
1321#endif // WEBRTC_USE_EPOLL
1322}
1323
1324void PhysicalSocketServer::Update(Dispatcher* pdispatcher) {
1325#if defined(WEBRTC_USE_EPOLL)
1326 if (epoll_fd_ == INVALID_SOCKET) {
1327 return;
1328 }
1329
1330 CritScope cs(&crit_);
1331 if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1332 return;
1333 }
1334
1335 UpdateEpoll(pdispatcher);
1336#endif
1337}
1338
1339void PhysicalSocketServer::AddRemovePendingDispatchers() {
1340 if (!pending_add_dispatchers_.empty()) {
1341 for (Dispatcher* pdispatcher : pending_add_dispatchers_) {
1342 dispatchers_.insert(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001343 }
jbauchde4db112017-05-31 13:09:18 -07001344 pending_add_dispatchers_.clear();
1345 }
1346
1347 if (!pending_remove_dispatchers_.empty()) {
1348 for (Dispatcher* pdispatcher : pending_remove_dispatchers_) {
1349 dispatchers_.erase(pdispatcher);
1350 }
1351 pending_remove_dispatchers_.clear();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001352 }
1353}
1354
1355#if defined(WEBRTC_POSIX)
jbauchde4db112017-05-31 13:09:18 -07001356
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001357bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
jbauchde4db112017-05-31 13:09:18 -07001358#if defined(WEBRTC_USE_EPOLL)
1359 // We don't keep a dedicated "epoll" descriptor containing only the non-IO
1360 // (i.e. signaling) dispatcher, so "poll" will be used instead of the default
1361 // "select" to support sockets larger than FD_SETSIZE.
1362 if (!process_io) {
1363 return WaitPoll(cmsWait, signal_wakeup_);
1364 } else if (epoll_fd_ != INVALID_SOCKET) {
1365 return WaitEpoll(cmsWait);
1366 }
1367#endif
1368 return WaitSelect(cmsWait, process_io);
1369}
1370
1371static void ProcessEvents(Dispatcher* dispatcher,
1372 bool readable,
1373 bool writable,
1374 bool check_error) {
1375 int errcode = 0;
1376 // TODO(pthatcher): Should we set errcode if getsockopt fails?
1377 if (check_error) {
1378 socklen_t len = sizeof(errcode);
1379 ::getsockopt(dispatcher->GetDescriptor(), SOL_SOCKET, SO_ERROR, &errcode,
1380 &len);
1381 }
1382
1383 uint32_t ff = 0;
1384
1385 // Check readable descriptors. If we're waiting on an accept, signal
1386 // that. Otherwise we're waiting for data, check to see if we're
1387 // readable or really closed.
1388 // TODO(pthatcher): Only peek at TCP descriptors.
1389 if (readable) {
1390 if (dispatcher->GetRequestedEvents() & DE_ACCEPT) {
1391 ff |= DE_ACCEPT;
1392 } else if (errcode || dispatcher->IsDescriptorClosed()) {
1393 ff |= DE_CLOSE;
1394 } else {
1395 ff |= DE_READ;
1396 }
1397 }
1398
1399 // Check writable descriptors. If we're waiting on a connect, detect
1400 // success versus failure by the reaped error code.
1401 if (writable) {
1402 if (dispatcher->GetRequestedEvents() & DE_CONNECT) {
1403 if (!errcode) {
1404 ff |= DE_CONNECT;
1405 } else {
1406 ff |= DE_CLOSE;
1407 }
1408 } else {
1409 ff |= DE_WRITE;
1410 }
1411 }
1412
1413 // Tell the descriptor about the event.
1414 if (ff != 0) {
1415 dispatcher->OnPreEvent(ff);
1416 dispatcher->OnEvent(ff, errcode);
1417 }
1418}
1419
1420bool PhysicalSocketServer::WaitSelect(int cmsWait, bool process_io) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001421 // Calculate timing information
1422
deadbeef37f5ecf2017-02-27 14:06:41 -08001423 struct timeval* ptvWait = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001424 struct timeval tvWait;
Niels Möller689b5872018-08-29 09:55:44 +02001425 int64_t stop_us;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001426 if (cmsWait != kForever) {
1427 // Calculate wait timeval
1428 tvWait.tv_sec = cmsWait / 1000;
1429 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1430 ptvWait = &tvWait;
1431
Niels Möller689b5872018-08-29 09:55:44 +02001432 // Calculate when to return
1433 stop_us = rtc::TimeMicros() + cmsWait * 1000;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001434 }
1435
1436 // Zero all fd_sets. Don't need to do this inside the loop since
1437 // select() zeros the descriptors not signaled
1438
1439 fd_set fdsRead;
1440 FD_ZERO(&fdsRead);
1441 fd_set fdsWrite;
1442 FD_ZERO(&fdsWrite);
Yves Gerey665174f2018-06-19 15:03:05 +02001443// Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1444// inline assembly in FD_ZERO.
1445// http://crbug.com/344505
pbos@webrtc.org27e58982014-10-07 17:56:53 +00001446#ifdef MEMORY_SANITIZER
1447 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1448 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1449#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001450
1451 fWait_ = true;
1452
1453 while (fWait_) {
1454 int fdmax = -1;
1455 {
1456 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001457 // TODO(jbauch): Support re-entrant waiting.
1458 RTC_DCHECK(!processing_dispatchers_);
1459 for (Dispatcher* pdispatcher : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001460 // Query dispatchers for read and write wait state
nisseede5da42017-01-12 05:15:36 -08001461 RTC_DCHECK(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001462 if (!process_io && (pdispatcher != signal_wakeup_))
1463 continue;
1464 int fd = pdispatcher->GetDescriptor();
jbauchde4db112017-05-31 13:09:18 -07001465 // "select"ing a file descriptor that is equal to or larger than
1466 // FD_SETSIZE will result in undefined behavior.
1467 RTC_DCHECK_LT(fd, FD_SETSIZE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001468 if (fd > fdmax)
1469 fdmax = fd;
1470
Peter Boström0c4e06b2015-10-07 12:23:21 +02001471 uint32_t ff = pdispatcher->GetRequestedEvents();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001472 if (ff & (DE_READ | DE_ACCEPT))
1473 FD_SET(fd, &fdsRead);
1474 if (ff & (DE_WRITE | DE_CONNECT))
1475 FD_SET(fd, &fdsWrite);
1476 }
1477 }
1478
1479 // Wait then call handlers as appropriate
1480 // < 0 means error
1481 // 0 means timeout
1482 // > 0 means count of descriptors ready
deadbeef37f5ecf2017-02-27 14:06:41 -08001483 int n = select(fdmax + 1, &fdsRead, &fdsWrite, nullptr, ptvWait);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001484
1485 // If error, return error.
1486 if (n < 0) {
1487 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001488 RTC_LOG_E(LS_ERROR, EN, errno) << "select";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001489 return false;
1490 }
1491 // Else ignore the error and keep going. If this EINTR was for one of the
1492 // signals managed by this PhysicalSocketServer, the
1493 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1494 // iteration.
1495 } else if (n == 0) {
1496 // If timeout, return success
1497 return true;
1498 } else {
1499 // We have signaled descriptors
1500 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001501 processing_dispatchers_ = true;
1502 for (Dispatcher* pdispatcher : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001503 int fd = pdispatcher->GetDescriptor();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001504
jbauchde4db112017-05-31 13:09:18 -07001505 bool readable = FD_ISSET(fd, &fdsRead);
1506 if (readable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001507 FD_CLR(fd, &fdsRead);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001508 }
1509
jbauchde4db112017-05-31 13:09:18 -07001510 bool writable = FD_ISSET(fd, &fdsWrite);
1511 if (writable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001512 FD_CLR(fd, &fdsWrite);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001513 }
1514
jbauchde4db112017-05-31 13:09:18 -07001515 // The error code can be signaled through reads or writes.
1516 ProcessEvents(pdispatcher, readable, writable, readable || writable);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001517 }
jbauchde4db112017-05-31 13:09:18 -07001518
1519 processing_dispatchers_ = false;
1520 // Process deferred dispatchers that have been added/removed while the
1521 // events were handled above.
1522 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001523 }
1524
1525 // Recalc the time remaining to wait. Doing it here means it doesn't get
1526 // calced twice the first time through the loop
1527 if (ptvWait) {
1528 ptvWait->tv_sec = 0;
1529 ptvWait->tv_usec = 0;
Niels Möller689b5872018-08-29 09:55:44 +02001530 int64_t time_left_us = stop_us - rtc::TimeMicros();
1531 if (time_left_us > 0) {
1532 ptvWait->tv_sec = time_left_us / rtc::kNumMicrosecsPerSec;
1533 ptvWait->tv_usec = time_left_us % rtc::kNumMicrosecsPerSec;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001534 }
1535 }
1536 }
1537
1538 return true;
1539}
1540
jbauchde4db112017-05-31 13:09:18 -07001541#if defined(WEBRTC_USE_EPOLL)
1542
1543// Initial number of events to process with one call to "epoll_wait".
1544static const size_t kInitialEpollEvents = 128;
1545
1546// Maximum number of events to process with one call to "epoll_wait".
1547static const size_t kMaxEpollEvents = 8192;
1548
1549void PhysicalSocketServer::AddEpoll(Dispatcher* pdispatcher) {
1550 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1551 int fd = pdispatcher->GetDescriptor();
1552 RTC_DCHECK(fd != INVALID_SOCKET);
1553 if (fd == INVALID_SOCKET) {
1554 return;
1555 }
1556
1557 struct epoll_event event = {0};
1558 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
1559 event.data.ptr = pdispatcher;
1560 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &event);
1561 RTC_DCHECK_EQ(err, 0);
1562 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001563 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_ADD";
jbauchde4db112017-05-31 13:09:18 -07001564 }
1565}
1566
1567void PhysicalSocketServer::RemoveEpoll(Dispatcher* pdispatcher) {
1568 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1569 int fd = pdispatcher->GetDescriptor();
1570 RTC_DCHECK(fd != INVALID_SOCKET);
1571 if (fd == INVALID_SOCKET) {
1572 return;
1573 }
1574
1575 struct epoll_event event = {0};
1576 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &event);
1577 RTC_DCHECK(err == 0 || errno == ENOENT);
1578 if (err == -1) {
1579 if (errno == ENOENT) {
1580 // Socket has already been closed.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001581 RTC_LOG_E(LS_VERBOSE, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001582 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001583 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001584 }
1585 }
1586}
1587
1588void PhysicalSocketServer::UpdateEpoll(Dispatcher* pdispatcher) {
1589 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1590 int fd = pdispatcher->GetDescriptor();
1591 RTC_DCHECK(fd != INVALID_SOCKET);
1592 if (fd == INVALID_SOCKET) {
1593 return;
1594 }
1595
1596 struct epoll_event event = {0};
1597 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
1598 event.data.ptr = pdispatcher;
1599 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &event);
1600 RTC_DCHECK_EQ(err, 0);
1601 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001602 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_MOD";
jbauchde4db112017-05-31 13:09:18 -07001603 }
1604}
1605
1606bool PhysicalSocketServer::WaitEpoll(int cmsWait) {
1607 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1608 int64_t tvWait = -1;
1609 int64_t tvStop = -1;
1610 if (cmsWait != kForever) {
1611 tvWait = cmsWait;
1612 tvStop = TimeAfter(cmsWait);
1613 }
1614
1615 if (epoll_events_.empty()) {
1616 // The initial space to receive events is created only if epoll is used.
1617 epoll_events_.resize(kInitialEpollEvents);
1618 }
1619
1620 fWait_ = true;
1621
1622 while (fWait_) {
1623 // Wait then call handlers as appropriate
1624 // < 0 means error
1625 // 0 means timeout
1626 // > 0 means count of descriptors ready
1627 int n = epoll_wait(epoll_fd_, &epoll_events_[0],
1628 static_cast<int>(epoll_events_.size()),
1629 static_cast<int>(tvWait));
1630 if (n < 0) {
1631 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001632 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll";
jbauchde4db112017-05-31 13:09:18 -07001633 return false;
1634 }
1635 // Else ignore the error and keep going. If this EINTR was for one of the
1636 // signals managed by this PhysicalSocketServer, the
1637 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1638 // iteration.
1639 } else if (n == 0) {
1640 // If timeout, return success
1641 return true;
1642 } else {
1643 // We have signaled descriptors
1644 CritScope cr(&crit_);
1645 for (int i = 0; i < n; ++i) {
1646 const epoll_event& event = epoll_events_[i];
1647 Dispatcher* pdispatcher = static_cast<Dispatcher*>(event.data.ptr);
1648 if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1649 // The dispatcher for this socket no longer exists.
1650 continue;
1651 }
1652
1653 bool readable = (event.events & (EPOLLIN | EPOLLPRI));
1654 bool writable = (event.events & EPOLLOUT);
1655 bool check_error = (event.events & (EPOLLRDHUP | EPOLLERR | EPOLLHUP));
1656
1657 ProcessEvents(pdispatcher, readable, writable, check_error);
1658 }
1659 }
1660
1661 if (static_cast<size_t>(n) == epoll_events_.size() &&
1662 epoll_events_.size() < kMaxEpollEvents) {
1663 // We used the complete space to receive events, increase size for future
1664 // iterations.
1665 epoll_events_.resize(std::max(epoll_events_.size() * 2, kMaxEpollEvents));
1666 }
1667
1668 if (cmsWait != kForever) {
1669 tvWait = TimeDiff(tvStop, TimeMillis());
1670 if (tvWait < 0) {
1671 // Return success on timeout.
1672 return true;
1673 }
1674 }
1675 }
1676
1677 return true;
1678}
1679
1680bool PhysicalSocketServer::WaitPoll(int cmsWait, Dispatcher* dispatcher) {
1681 RTC_DCHECK(dispatcher);
1682 int64_t tvWait = -1;
1683 int64_t tvStop = -1;
1684 if (cmsWait != kForever) {
1685 tvWait = cmsWait;
1686 tvStop = TimeAfter(cmsWait);
1687 }
1688
1689 fWait_ = true;
1690
1691 struct pollfd fds = {0};
1692 int fd = dispatcher->GetDescriptor();
1693 fds.fd = fd;
1694
1695 while (fWait_) {
1696 uint32_t ff = dispatcher->GetRequestedEvents();
1697 fds.events = 0;
1698 if (ff & (DE_READ | DE_ACCEPT)) {
1699 fds.events |= POLLIN;
1700 }
1701 if (ff & (DE_WRITE | DE_CONNECT)) {
1702 fds.events |= POLLOUT;
1703 }
1704 fds.revents = 0;
1705
1706 // Wait then call handlers as appropriate
1707 // < 0 means error
1708 // 0 means timeout
1709 // > 0 means count of descriptors ready
1710 int n = poll(&fds, 1, static_cast<int>(tvWait));
1711 if (n < 0) {
1712 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001713 RTC_LOG_E(LS_ERROR, EN, errno) << "poll";
jbauchde4db112017-05-31 13:09:18 -07001714 return false;
1715 }
1716 // Else ignore the error and keep going. If this EINTR was for one of the
1717 // signals managed by this PhysicalSocketServer, the
1718 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1719 // iteration.
1720 } else if (n == 0) {
1721 // If timeout, return success
1722 return true;
1723 } else {
1724 // We have signaled descriptors (should only be the passed dispatcher).
1725 RTC_DCHECK_EQ(n, 1);
1726 RTC_DCHECK_EQ(fds.fd, fd);
1727
1728 bool readable = (fds.revents & (POLLIN | POLLPRI));
1729 bool writable = (fds.revents & POLLOUT);
1730 bool check_error = (fds.revents & (POLLRDHUP | POLLERR | POLLHUP));
1731
1732 ProcessEvents(dispatcher, readable, writable, check_error);
1733 }
1734
1735 if (cmsWait != kForever) {
1736 tvWait = TimeDiff(tvStop, TimeMillis());
1737 if (tvWait < 0) {
1738 // Return success on timeout.
1739 return true;
1740 }
1741 }
1742 }
1743
1744 return true;
1745}
1746
1747#endif // WEBRTC_USE_EPOLL
1748
Mirko Bonadeiff88a642020-05-13 13:48:11 +00001749static void GlobalSignalHandler(int signum) {
1750 PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
1751}
1752
1753bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
1754 void (*handler)(int)) {
1755 // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
1756 // otherwise set one.
1757 if (handler == SIG_IGN || handler == SIG_DFL) {
1758 if (!InstallSignal(signum, handler)) {
1759 return false;
1760 }
1761 if (signal_dispatcher_) {
1762 signal_dispatcher_->ClearHandler(signum);
1763 if (!signal_dispatcher_->HasHandlers()) {
1764 signal_dispatcher_.reset();
1765 }
1766 }
1767 } else {
1768 if (!signal_dispatcher_) {
1769 signal_dispatcher_.reset(new PosixSignalDispatcher(this));
1770 }
1771 signal_dispatcher_->SetHandler(signum, handler);
1772 if (!InstallSignal(signum, &GlobalSignalHandler)) {
1773 return false;
1774 }
1775 }
1776 return true;
1777}
1778
1779Dispatcher* PhysicalSocketServer::signal_dispatcher() {
1780 return signal_dispatcher_.get();
1781}
1782
1783bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
1784 struct sigaction act;
1785 // It doesn't really matter what we set this mask to.
1786 if (sigemptyset(&act.sa_mask) != 0) {
1787 RTC_LOG_ERR(LS_ERROR) << "Couldn't set mask";
1788 return false;
1789 }
1790 act.sa_handler = handler;
1791#if !defined(__native_client__)
1792 // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
1793 // and it's a nuisance. Though some syscalls still return EINTR and there's no
1794 // real standard for which ones. :(
1795 act.sa_flags = SA_RESTART;
1796#else
1797 act.sa_flags = 0;
1798#endif
1799 if (sigaction(signum, &act, nullptr) != 0) {
1800 RTC_LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
1801 return false;
1802 }
1803 return true;
1804}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001805#endif // WEBRTC_POSIX
1806
1807#if defined(WEBRTC_WIN)
1808bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
Honghai Zhang82d78622016-05-06 11:29:15 -07001809 int64_t cmsTotal = cmsWait;
1810 int64_t cmsElapsed = 0;
1811 int64_t msStart = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001812
1813 fWait_ = true;
1814 while (fWait_) {
1815 std::vector<WSAEVENT> events;
Yves Gerey665174f2018-06-19 15:03:05 +02001816 std::vector<Dispatcher*> event_owners;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001817
1818 events.push_back(socket_ev_);
1819
1820 {
1821 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001822 // TODO(jbauch): Support re-entrant waiting.
1823 RTC_DCHECK(!processing_dispatchers_);
1824
1825 // Calling "CheckSignalClose" might remove a closed dispatcher from the
1826 // set. This must be deferred to prevent invalidating the iterator.
1827 processing_dispatchers_ = true;
1828 for (Dispatcher* disp : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001829 if (!process_io && (disp != signal_wakeup_))
1830 continue;
1831 SOCKET s = disp->GetSocket();
1832 if (disp->CheckSignalClose()) {
1833 // We just signalled close, don't poll this socket
1834 } else if (s != INVALID_SOCKET) {
Yves Gerey665174f2018-06-19 15:03:05 +02001835 WSAEventSelect(s, events[0],
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001836 FlagsToEvents(disp->GetRequestedEvents()));
1837 } else {
1838 events.push_back(disp->GetWSAEvent());
1839 event_owners.push_back(disp);
1840 }
1841 }
jbauchde4db112017-05-31 13:09:18 -07001842
1843 processing_dispatchers_ = false;
1844 // Process deferred dispatchers that have been added/removed while the
1845 // events were handled above.
1846 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001847 }
1848
1849 // Which is shorter, the delay wait or the asked wait?
1850
Honghai Zhang82d78622016-05-06 11:29:15 -07001851 int64_t cmsNext;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001852 if (cmsWait == kForever) {
1853 cmsNext = cmsWait;
1854 } else {
Honghai Zhang82d78622016-05-06 11:29:15 -07001855 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001856 }
1857
1858 // Wait for one of the events to signal
Yves Gerey665174f2018-06-19 15:03:05 +02001859 DWORD dw =
1860 WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()), &events[0],
1861 false, static_cast<DWORD>(cmsNext), false);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001862
1863 if (dw == WSA_WAIT_FAILED) {
1864 // Failed?
jbauch095ae152015-12-18 01:39:55 -08001865 // TODO(pthatcher): need a better strategy than this!
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001866 WSAGetLastError();
nissec80e7412017-01-11 05:56:46 -08001867 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001868 return false;
1869 } else if (dw == WSA_WAIT_TIMEOUT) {
1870 // Timeout?
1871 return true;
1872 } else {
1873 // Figure out which one it is and call it
1874 CritScope cr(&crit_);
1875 int index = dw - WSA_WAIT_EVENT_0;
1876 if (index > 0) {
Yves Gerey665174f2018-06-19 15:03:05 +02001877 --index; // The first event is the socket event
jbauchde4db112017-05-31 13:09:18 -07001878 Dispatcher* disp = event_owners[index];
1879 // The dispatcher could have been removed while waiting for events.
1880 if (dispatchers_.find(disp) != dispatchers_.end()) {
1881 disp->OnPreEvent(0);
1882 disp->OnEvent(0, 0);
1883 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001884 } else if (process_io) {
jbauchde4db112017-05-31 13:09:18 -07001885 processing_dispatchers_ = true;
1886 for (Dispatcher* disp : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001887 SOCKET s = disp->GetSocket();
1888 if (s == INVALID_SOCKET)
1889 continue;
1890
1891 WSANETWORKEVENTS wsaEvents;
1892 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1893 if (err == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001894 {
1895 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1896 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001897 RTC_LOG(WARNING)
1898 << "PhysicalSocketServer got FD_READ_BIT error "
1899 << wsaEvents.iErrorCode[FD_READ_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001900 }
1901 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1902 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001903 RTC_LOG(WARNING)
1904 << "PhysicalSocketServer got FD_WRITE_BIT error "
1905 << wsaEvents.iErrorCode[FD_WRITE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001906 }
1907 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1908 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001909 RTC_LOG(WARNING)
1910 << "PhysicalSocketServer got FD_CONNECT_BIT error "
1911 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001912 }
1913 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1914 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001915 RTC_LOG(WARNING)
1916 << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1917 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001918 }
1919 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1920 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001921 RTC_LOG(WARNING)
1922 << "PhysicalSocketServer got FD_CLOSE_BIT error "
1923 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001924 }
1925 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001926 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001927 int errcode = 0;
1928 if (wsaEvents.lNetworkEvents & FD_READ)
1929 ff |= DE_READ;
1930 if (wsaEvents.lNetworkEvents & FD_WRITE)
1931 ff |= DE_WRITE;
1932 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1933 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1934 ff |= DE_CONNECT;
1935 } else {
1936 ff |= DE_CLOSE;
1937 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1938 }
1939 }
1940 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1941 ff |= DE_ACCEPT;
1942 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1943 ff |= DE_CLOSE;
1944 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1945 }
1946 if (ff != 0) {
1947 disp->OnPreEvent(ff);
1948 disp->OnEvent(ff, errcode);
1949 }
1950 }
1951 }
jbauchde4db112017-05-31 13:09:18 -07001952
1953 processing_dispatchers_ = false;
1954 // Process deferred dispatchers that have been added/removed while the
1955 // events were handled above.
1956 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001957 }
1958
1959 // Reset the network event until new activity occurs
1960 WSAResetEvent(socket_ev_);
1961 }
1962
1963 // Break?
1964 if (!fWait_)
1965 break;
1966 cmsElapsed = TimeSince(msStart);
1967 if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
Yves Gerey665174f2018-06-19 15:03:05 +02001968 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001969 }
1970 }
1971
1972 // Done
1973 return true;
1974}
honghaizcec0a082016-01-15 14:49:09 -08001975#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001976
1977} // namespace rtc