blob: 0cbcb8130c60f418b467ae2fc5e91d800a1bc4e3 [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
henrike@webrtc.orgf0488722014-05-13 18:00:26 +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
897 ss_->Remove(this);
898 return PhysicalSocket::Close();
899}
900
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000901#if defined(WEBRTC_POSIX)
902class EventDispatcher : public Dispatcher {
903 public:
904 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
905 if (pipe(afd_) < 0)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100906 RTC_LOG(LERROR) << "pipe failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000907 ss_->Add(this);
908 }
909
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000910 ~EventDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000911 ss_->Remove(this);
912 close(afd_[0]);
913 close(afd_[1]);
914 }
915
916 virtual void Signal() {
917 CritScope cs(&crit_);
918 if (!fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200919 const uint8_t b[1] = {0};
nissec16fa5e2017-02-07 07:18:43 -0800920 const ssize_t res = write(afd_[1], b, sizeof(b));
921 RTC_DCHECK_EQ(1, res);
922 fSignaled_ = true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000923 }
924 }
925
Peter Boström0c4e06b2015-10-07 12:23:21 +0200926 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000927
Peter Boström0c4e06b2015-10-07 12:23:21 +0200928 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000929 // It is not possible to perfectly emulate an auto-resetting event with
930 // pipes. This simulates it by resetting before the event is handled.
931
932 CritScope cs(&crit_);
933 if (fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200934 uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
nissec16fa5e2017-02-07 07:18:43 -0800935 const ssize_t res = read(afd_[0], b, sizeof(b));
936 RTC_DCHECK_EQ(1, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000937 fSignaled_ = false;
938 }
939 }
940
nissec80e7412017-01-11 05:56:46 -0800941 void OnEvent(uint32_t ff, int err) override { RTC_NOTREACHED(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000942
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000943 int GetDescriptor() override { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000944
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000945 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000946
947 private:
Yves Gerey665174f2018-06-19 15:03:05 +0200948 PhysicalSocketServer* ss_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000949 int afd_[2];
950 bool fSignaled_;
951 CriticalSection crit_;
952};
953
954// These two classes use the self-pipe trick to deliver POSIX signals to our
955// select loop. This is the only safe, reliable, cross-platform way to do
956// non-trivial things with a POSIX signal in an event-driven program (until
957// proper pselect() implementations become ubiquitous).
958
959class PosixSignalHandler {
960 public:
961 // POSIX only specifies 32 signals, but in principle the system might have
962 // more and the programmer might choose to use them, so we size our array
963 // for 128.
964 static const int kNumPosixSignals = 128;
965
966 // There is just a single global instance. (Signal handlers do not get any
967 // sort of user-defined void * parameter, so they can't access anything that
968 // isn't global.)
969 static PosixSignalHandler* Instance() {
Niels Möller14682a32018-05-24 08:54:25 +0200970 static PosixSignalHandler* const instance = new PosixSignalHandler();
971 return instance;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000972 }
973
974 // Returns true if the given signal number is set.
975 bool IsSignalSet(int signum) const {
nisseede5da42017-01-12 05:15:36 -0800976 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800977 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000978 return received_signal_[signum];
979 } else {
980 return false;
981 }
982 }
983
984 // Clears the given signal number.
985 void ClearSignal(int signum) {
nisseede5da42017-01-12 05:15:36 -0800986 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800987 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000988 received_signal_[signum] = false;
989 }
990 }
991
992 // Returns the file descriptor to monitor for signal events.
Yves Gerey665174f2018-06-19 15:03:05 +0200993 int GetDescriptor() const { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000994
995 // This is called directly from our real signal handler, so it must be
996 // signal-handler-safe. That means it cannot assume anything about the
997 // user-level state of the process, since the handler could be executed at any
998 // time on any thread.
999 void OnPosixSignalReceived(int signum) {
tfarina5237aaf2015-11-10 23:44:30 -08001000 if (signum >= static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001001 // We don't have space in our array for this.
1002 return;
1003 }
1004 // Set a flag saying we've seen this signal.
1005 received_signal_[signum] = true;
1006 // Notify application code that we got a signal.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001007 const uint8_t b[1] = {0};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001008 if (-1 == write(afd_[1], b, sizeof(b))) {
1009 // Nothing we can do here. If there's an error somehow then there's
1010 // nothing we can safely do from a signal handler.
1011 // No, we can't even safely log it.
1012 // But, we still have to check the return value here. Otherwise,
1013 // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
1014 return;
1015 }
1016 }
1017
1018 private:
1019 PosixSignalHandler() {
1020 if (pipe(afd_) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001021 RTC_LOG_ERR(LS_ERROR) << "pipe failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001022 return;
1023 }
1024 if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001025 RTC_LOG_ERR(LS_WARNING) << "fcntl #1 failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001026 }
1027 if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001028 RTC_LOG_ERR(LS_WARNING) << "fcntl #2 failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001029 }
Yves Gerey665174f2018-06-19 15:03:05 +02001030 memset(const_cast<void*>(static_cast<volatile void*>(received_signal_)), 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001031 sizeof(received_signal_));
1032 }
1033
1034 ~PosixSignalHandler() {
1035 int fd1 = afd_[0];
1036 int fd2 = afd_[1];
1037 // We clobber the stored file descriptor numbers here or else in principle
1038 // a signal that happens to be delivered during application termination
1039 // could erroneously write a zero byte to an unrelated file handle in
1040 // OnPosixSignalReceived() if some other file happens to be opened later
1041 // during shutdown and happens to be given the same file descriptor number
1042 // as our pipe had. Unfortunately even with this precaution there is still a
1043 // race where that could occur if said signal happens to be handled
1044 // concurrently with this code and happens to have already read the value of
1045 // afd_[1] from memory before we clobber it, but that's unlikely.
1046 afd_[0] = -1;
1047 afd_[1] = -1;
1048 close(fd1);
1049 close(fd2);
1050 }
1051
1052 int afd_[2];
1053 // These are boolean flags that will be set in our signal handler and read
1054 // and cleared from Wait(). There is a race involved in this, but it is
1055 // benign. The signal handler sets the flag before signaling the pipe, so
1056 // we'll never end up blocking in select() while a flag is still true.
1057 // However, if two of the same signal arrive close to each other then it's
1058 // possible that the second time the handler may set the flag while it's still
1059 // true, meaning that signal will be missed. But the first occurrence of it
1060 // will still be handled, so this isn't a problem.
1061 // Volatile is not necessary here for correctness, but this data _is_ volatile
1062 // so I've marked it as such.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001063 volatile uint8_t received_signal_[kNumPosixSignals];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001064};
1065
1066class PosixSignalDispatcher : public Dispatcher {
1067 public:
Yves Gerey665174f2018-06-19 15:03:05 +02001068 PosixSignalDispatcher(PhysicalSocketServer* owner) : owner_(owner) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001069 owner_->Add(this);
1070 }
1071
Yves Gerey665174f2018-06-19 15:03:05 +02001072 ~PosixSignalDispatcher() override { owner_->Remove(this); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001073
Peter Boström0c4e06b2015-10-07 12:23:21 +02001074 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001075
Peter Boström0c4e06b2015-10-07 12:23:21 +02001076 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001077 // Events might get grouped if signals come very fast, so we read out up to
1078 // 16 bytes to make sure we keep the pipe empty.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001079 uint8_t b[16];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001080 ssize_t ret = read(GetDescriptor(), b, sizeof(b));
1081 if (ret < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001082 RTC_LOG_ERR(LS_WARNING) << "Error in read()";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001083 } else if (ret == 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001084 RTC_LOG(LS_WARNING) << "Should have read at least one byte";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001085 }
1086 }
1087
Peter Boström0c4e06b2015-10-07 12:23:21 +02001088 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001089 for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
1090 ++signum) {
1091 if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
1092 PosixSignalHandler::Instance()->ClearSignal(signum);
1093 HandlerMap::iterator i = handlers_.find(signum);
1094 if (i == handlers_.end()) {
1095 // This can happen if a signal is delivered to our process at around
1096 // the same time as we unset our handler for it. It is not an error
1097 // condition, but it's unusual enough to be worth logging.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001098 RTC_LOG(LS_INFO) << "Received signal with no handler: " << signum;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001099 } else {
1100 // Otherwise, execute our handler.
1101 (*i->second)(signum);
1102 }
1103 }
1104 }
1105 }
1106
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001107 int GetDescriptor() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001108 return PosixSignalHandler::Instance()->GetDescriptor();
1109 }
1110
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001111 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001112
1113 void SetHandler(int signum, void (*handler)(int)) {
1114 handlers_[signum] = handler;
1115 }
1116
Yves Gerey665174f2018-06-19 15:03:05 +02001117 void ClearHandler(int signum) { handlers_.erase(signum); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001118
Yves Gerey665174f2018-06-19 15:03:05 +02001119 bool HasHandlers() { return !handlers_.empty(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001120
1121 private:
1122 typedef std::map<int, void (*)(int)> HandlerMap;
1123
1124 HandlerMap handlers_;
1125 // Our owner.
Yves Gerey665174f2018-06-19 15:03:05 +02001126 PhysicalSocketServer* owner_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001127};
1128
Yves Gerey665174f2018-06-19 15:03:05 +02001129#endif // WEBRTC_POSIX
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001130
1131#if defined(WEBRTC_WIN)
Peter Boström0c4e06b2015-10-07 12:23:21 +02001132static uint32_t FlagsToEvents(uint32_t events) {
1133 uint32_t ffFD = FD_CLOSE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001134 if (events & DE_READ)
1135 ffFD |= FD_READ;
1136 if (events & DE_WRITE)
1137 ffFD |= FD_WRITE;
1138 if (events & DE_CONNECT)
1139 ffFD |= FD_CONNECT;
1140 if (events & DE_ACCEPT)
1141 ffFD |= FD_ACCEPT;
1142 return ffFD;
1143}
1144
1145class EventDispatcher : public Dispatcher {
1146 public:
Yves Gerey665174f2018-06-19 15:03:05 +02001147 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001148 hev_ = WSACreateEvent();
1149 if (hev_) {
1150 ss_->Add(this);
1151 }
1152 }
1153
Steve Anton9de3aac2017-10-24 10:08:26 -07001154 ~EventDispatcher() override {
deadbeef37f5ecf2017-02-27 14:06:41 -08001155 if (hev_ != nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001156 ss_->Remove(this);
1157 WSACloseEvent(hev_);
deadbeef37f5ecf2017-02-27 14:06:41 -08001158 hev_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001159 }
1160 }
1161
1162 virtual void Signal() {
deadbeef37f5ecf2017-02-27 14:06:41 -08001163 if (hev_ != nullptr)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001164 WSASetEvent(hev_);
1165 }
1166
Steve Anton9de3aac2017-10-24 10:08:26 -07001167 uint32_t GetRequestedEvents() override { return 0; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001168
Steve Anton9de3aac2017-10-24 10:08:26 -07001169 void OnPreEvent(uint32_t ff) override { WSAResetEvent(hev_); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001170
Steve Anton9de3aac2017-10-24 10:08:26 -07001171 void OnEvent(uint32_t ff, int err) override {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001172
Steve Anton9de3aac2017-10-24 10:08:26 -07001173 WSAEVENT GetWSAEvent() override { return hev_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001174
Steve Anton9de3aac2017-10-24 10:08:26 -07001175 SOCKET GetSocket() override { return INVALID_SOCKET; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001176
Steve Anton9de3aac2017-10-24 10:08:26 -07001177 bool CheckSignalClose() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001178
Steve Anton9de3aac2017-10-24 10:08:26 -07001179 private:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001180 PhysicalSocketServer* ss_;
1181 WSAEVENT hev_;
1182};
honghaizcec0a082016-01-15 14:49:09 -08001183#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001184
1185// Sets the value of a boolean value to false when signaled.
1186class Signaler : public EventDispatcher {
1187 public:
Yves Gerey665174f2018-06-19 15:03:05 +02001188 Signaler(PhysicalSocketServer* ss, bool* pf) : EventDispatcher(ss), pf_(pf) {}
1189 ~Signaler() override {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001190
Peter Boström0c4e06b2015-10-07 12:23:21 +02001191 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001192 if (pf_)
1193 *pf_ = false;
1194 }
1195
1196 private:
Yves Gerey665174f2018-06-19 15:03:05 +02001197 bool* pf_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001198};
1199
Yves Gerey665174f2018-06-19 15:03:05 +02001200PhysicalSocketServer::PhysicalSocketServer() : fWait_(false) {
jbauchde4db112017-05-31 13:09:18 -07001201#if defined(WEBRTC_USE_EPOLL)
1202 // Since Linux 2.6.8, the size argument is ignored, but must be greater than
1203 // zero. Before that the size served as hint to the kernel for the amount of
1204 // space to initially allocate in internal data structures.
1205 epoll_fd_ = epoll_create(FD_SETSIZE);
1206 if (epoll_fd_ == -1) {
1207 // Not an error, will fall back to "select" below.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001208 RTC_LOG_E(LS_WARNING, EN, errno) << "epoll_create";
jbauchde4db112017-05-31 13:09:18 -07001209 epoll_fd_ = INVALID_SOCKET;
1210 }
1211#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001212 signal_wakeup_ = new Signaler(this, &fWait_);
1213#if defined(WEBRTC_WIN)
1214 socket_ev_ = WSACreateEvent();
1215#endif
1216}
1217
1218PhysicalSocketServer::~PhysicalSocketServer() {
1219#if defined(WEBRTC_WIN)
1220 WSACloseEvent(socket_ev_);
1221#endif
1222#if defined(WEBRTC_POSIX)
1223 signal_dispatcher_.reset();
1224#endif
1225 delete signal_wakeup_;
jbauchde4db112017-05-31 13:09:18 -07001226#if defined(WEBRTC_USE_EPOLL)
1227 if (epoll_fd_ != INVALID_SOCKET) {
1228 close(epoll_fd_);
1229 }
1230#endif
nisseede5da42017-01-12 05:15:36 -08001231 RTC_DCHECK(dispatchers_.empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001232}
1233
1234void PhysicalSocketServer::WakeUp() {
1235 signal_wakeup_->Signal();
1236}
1237
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001238Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
1239 PhysicalSocket* socket = new PhysicalSocket(this);
1240 if (socket->Create(family, type)) {
1241 return socket;
1242 } else {
1243 delete socket;
jbauch095ae152015-12-18 01:39:55 -08001244 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001245 }
1246}
1247
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001248AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
1249 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1250 if (dispatcher->Create(family, type)) {
1251 return dispatcher;
1252 } else {
1253 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001254 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001255 }
1256}
1257
1258AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
1259 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1260 if (dispatcher->Initialize()) {
1261 return dispatcher;
1262 } else {
1263 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001264 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001265 }
1266}
1267
Yves Gerey665174f2018-06-19 15:03:05 +02001268void PhysicalSocketServer::Add(Dispatcher* pdispatcher) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001269 CritScope cs(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001270 if (processing_dispatchers_) {
1271 // A dispatcher is being added while a "Wait" call is processing the
1272 // list of socket events.
1273 // Defer adding to "dispatchers_" set until processing is done to avoid
1274 // invalidating the iterator in "Wait".
1275 pending_remove_dispatchers_.erase(pdispatcher);
1276 pending_add_dispatchers_.insert(pdispatcher);
1277 } else {
1278 dispatchers_.insert(pdispatcher);
1279 }
1280#if defined(WEBRTC_USE_EPOLL)
1281 if (epoll_fd_ != INVALID_SOCKET) {
1282 AddEpoll(pdispatcher);
1283 }
1284#endif // WEBRTC_USE_EPOLL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001285}
1286
Yves Gerey665174f2018-06-19 15:03:05 +02001287void PhysicalSocketServer::Remove(Dispatcher* pdispatcher) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001288 CritScope cs(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001289 if (processing_dispatchers_) {
1290 // A dispatcher is being removed while a "Wait" call is processing the
1291 // list of socket events.
1292 // Defer removal from "dispatchers_" set until processing is done to avoid
1293 // invalidating the iterator in "Wait".
1294 if (!pending_add_dispatchers_.erase(pdispatcher) &&
1295 dispatchers_.find(pdispatcher) == dispatchers_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001296 RTC_LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
Jonas Olssonb2b20312020-01-14 12:11:31 +01001297 "dispatcher, potentially from a duplicate call to "
1298 "Add.";
jbauchde4db112017-05-31 13:09:18 -07001299 return;
1300 }
1301
1302 pending_remove_dispatchers_.insert(pdispatcher);
1303 } else if (!dispatchers_.erase(pdispatcher)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001304 RTC_LOG(LS_WARNING)
1305 << "PhysicalSocketServer asked to remove a unknown "
Jonas Olssonb2b20312020-01-14 12:11:31 +01001306 "dispatcher, potentially from a duplicate call to Add.";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001307 return;
1308 }
jbauchde4db112017-05-31 13:09:18 -07001309#if defined(WEBRTC_USE_EPOLL)
1310 if (epoll_fd_ != INVALID_SOCKET) {
1311 RemoveEpoll(pdispatcher);
1312 }
1313#endif // WEBRTC_USE_EPOLL
1314}
1315
1316void PhysicalSocketServer::Update(Dispatcher* pdispatcher) {
1317#if defined(WEBRTC_USE_EPOLL)
1318 if (epoll_fd_ == INVALID_SOCKET) {
1319 return;
1320 }
1321
1322 CritScope cs(&crit_);
1323 if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1324 return;
1325 }
1326
1327 UpdateEpoll(pdispatcher);
1328#endif
1329}
1330
1331void PhysicalSocketServer::AddRemovePendingDispatchers() {
1332 if (!pending_add_dispatchers_.empty()) {
1333 for (Dispatcher* pdispatcher : pending_add_dispatchers_) {
1334 dispatchers_.insert(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001335 }
jbauchde4db112017-05-31 13:09:18 -07001336 pending_add_dispatchers_.clear();
1337 }
1338
1339 if (!pending_remove_dispatchers_.empty()) {
1340 for (Dispatcher* pdispatcher : pending_remove_dispatchers_) {
1341 dispatchers_.erase(pdispatcher);
1342 }
1343 pending_remove_dispatchers_.clear();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001344 }
1345}
1346
1347#if defined(WEBRTC_POSIX)
jbauchde4db112017-05-31 13:09:18 -07001348
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001349bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
jbauchde4db112017-05-31 13:09:18 -07001350#if defined(WEBRTC_USE_EPOLL)
1351 // We don't keep a dedicated "epoll" descriptor containing only the non-IO
1352 // (i.e. signaling) dispatcher, so "poll" will be used instead of the default
1353 // "select" to support sockets larger than FD_SETSIZE.
1354 if (!process_io) {
1355 return WaitPoll(cmsWait, signal_wakeup_);
1356 } else if (epoll_fd_ != INVALID_SOCKET) {
1357 return WaitEpoll(cmsWait);
1358 }
1359#endif
1360 return WaitSelect(cmsWait, process_io);
1361}
1362
1363static void ProcessEvents(Dispatcher* dispatcher,
1364 bool readable,
1365 bool writable,
1366 bool check_error) {
1367 int errcode = 0;
1368 // TODO(pthatcher): Should we set errcode if getsockopt fails?
1369 if (check_error) {
1370 socklen_t len = sizeof(errcode);
1371 ::getsockopt(dispatcher->GetDescriptor(), SOL_SOCKET, SO_ERROR, &errcode,
1372 &len);
1373 }
1374
1375 uint32_t ff = 0;
1376
1377 // Check readable descriptors. If we're waiting on an accept, signal
1378 // that. Otherwise we're waiting for data, check to see if we're
1379 // readable or really closed.
1380 // TODO(pthatcher): Only peek at TCP descriptors.
1381 if (readable) {
1382 if (dispatcher->GetRequestedEvents() & DE_ACCEPT) {
1383 ff |= DE_ACCEPT;
1384 } else if (errcode || dispatcher->IsDescriptorClosed()) {
1385 ff |= DE_CLOSE;
1386 } else {
1387 ff |= DE_READ;
1388 }
1389 }
1390
1391 // Check writable descriptors. If we're waiting on a connect, detect
1392 // success versus failure by the reaped error code.
1393 if (writable) {
1394 if (dispatcher->GetRequestedEvents() & DE_CONNECT) {
1395 if (!errcode) {
1396 ff |= DE_CONNECT;
1397 } else {
1398 ff |= DE_CLOSE;
1399 }
1400 } else {
1401 ff |= DE_WRITE;
1402 }
1403 }
1404
1405 // Tell the descriptor about the event.
1406 if (ff != 0) {
1407 dispatcher->OnPreEvent(ff);
1408 dispatcher->OnEvent(ff, errcode);
1409 }
1410}
1411
1412bool PhysicalSocketServer::WaitSelect(int cmsWait, bool process_io) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001413 // Calculate timing information
1414
deadbeef37f5ecf2017-02-27 14:06:41 -08001415 struct timeval* ptvWait = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001416 struct timeval tvWait;
Niels Möller689b5872018-08-29 09:55:44 +02001417 int64_t stop_us;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001418 if (cmsWait != kForever) {
1419 // Calculate wait timeval
1420 tvWait.tv_sec = cmsWait / 1000;
1421 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1422 ptvWait = &tvWait;
1423
Niels Möller689b5872018-08-29 09:55:44 +02001424 // Calculate when to return
1425 stop_us = rtc::TimeMicros() + cmsWait * 1000;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001426 }
1427
1428 // Zero all fd_sets. Don't need to do this inside the loop since
1429 // select() zeros the descriptors not signaled
1430
1431 fd_set fdsRead;
1432 FD_ZERO(&fdsRead);
1433 fd_set fdsWrite;
1434 FD_ZERO(&fdsWrite);
Yves Gerey665174f2018-06-19 15:03:05 +02001435// Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1436// inline assembly in FD_ZERO.
1437// http://crbug.com/344505
pbos@webrtc.org27e58982014-10-07 17:56:53 +00001438#ifdef MEMORY_SANITIZER
1439 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1440 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1441#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001442
1443 fWait_ = true;
1444
1445 while (fWait_) {
1446 int fdmax = -1;
1447 {
1448 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001449 // TODO(jbauch): Support re-entrant waiting.
1450 RTC_DCHECK(!processing_dispatchers_);
1451 for (Dispatcher* pdispatcher : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001452 // Query dispatchers for read and write wait state
nisseede5da42017-01-12 05:15:36 -08001453 RTC_DCHECK(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001454 if (!process_io && (pdispatcher != signal_wakeup_))
1455 continue;
1456 int fd = pdispatcher->GetDescriptor();
jbauchde4db112017-05-31 13:09:18 -07001457 // "select"ing a file descriptor that is equal to or larger than
1458 // FD_SETSIZE will result in undefined behavior.
1459 RTC_DCHECK_LT(fd, FD_SETSIZE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001460 if (fd > fdmax)
1461 fdmax = fd;
1462
Peter Boström0c4e06b2015-10-07 12:23:21 +02001463 uint32_t ff = pdispatcher->GetRequestedEvents();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001464 if (ff & (DE_READ | DE_ACCEPT))
1465 FD_SET(fd, &fdsRead);
1466 if (ff & (DE_WRITE | DE_CONNECT))
1467 FD_SET(fd, &fdsWrite);
1468 }
1469 }
1470
1471 // Wait then call handlers as appropriate
1472 // < 0 means error
1473 // 0 means timeout
1474 // > 0 means count of descriptors ready
deadbeef37f5ecf2017-02-27 14:06:41 -08001475 int n = select(fdmax + 1, &fdsRead, &fdsWrite, nullptr, ptvWait);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001476
1477 // If error, return error.
1478 if (n < 0) {
1479 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001480 RTC_LOG_E(LS_ERROR, EN, errno) << "select";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001481 return false;
1482 }
1483 // Else ignore the error and keep going. If this EINTR was for one of the
1484 // signals managed by this PhysicalSocketServer, the
1485 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1486 // iteration.
1487 } else if (n == 0) {
1488 // If timeout, return success
1489 return true;
1490 } else {
1491 // We have signaled descriptors
1492 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001493 processing_dispatchers_ = true;
1494 for (Dispatcher* pdispatcher : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001495 int fd = pdispatcher->GetDescriptor();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001496
jbauchde4db112017-05-31 13:09:18 -07001497 bool readable = FD_ISSET(fd, &fdsRead);
1498 if (readable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001499 FD_CLR(fd, &fdsRead);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001500 }
1501
jbauchde4db112017-05-31 13:09:18 -07001502 bool writable = FD_ISSET(fd, &fdsWrite);
1503 if (writable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001504 FD_CLR(fd, &fdsWrite);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001505 }
1506
jbauchde4db112017-05-31 13:09:18 -07001507 // The error code can be signaled through reads or writes.
1508 ProcessEvents(pdispatcher, readable, writable, readable || writable);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001509 }
jbauchde4db112017-05-31 13:09:18 -07001510
1511 processing_dispatchers_ = false;
1512 // Process deferred dispatchers that have been added/removed while the
1513 // events were handled above.
1514 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001515 }
1516
1517 // Recalc the time remaining to wait. Doing it here means it doesn't get
1518 // calced twice the first time through the loop
1519 if (ptvWait) {
1520 ptvWait->tv_sec = 0;
1521 ptvWait->tv_usec = 0;
Niels Möller689b5872018-08-29 09:55:44 +02001522 int64_t time_left_us = stop_us - rtc::TimeMicros();
1523 if (time_left_us > 0) {
1524 ptvWait->tv_sec = time_left_us / rtc::kNumMicrosecsPerSec;
1525 ptvWait->tv_usec = time_left_us % rtc::kNumMicrosecsPerSec;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001526 }
1527 }
1528 }
1529
1530 return true;
1531}
1532
jbauchde4db112017-05-31 13:09:18 -07001533#if defined(WEBRTC_USE_EPOLL)
1534
1535// Initial number of events to process with one call to "epoll_wait".
1536static const size_t kInitialEpollEvents = 128;
1537
1538// Maximum number of events to process with one call to "epoll_wait".
1539static const size_t kMaxEpollEvents = 8192;
1540
1541void PhysicalSocketServer::AddEpoll(Dispatcher* pdispatcher) {
1542 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1543 int fd = pdispatcher->GetDescriptor();
1544 RTC_DCHECK(fd != INVALID_SOCKET);
1545 if (fd == INVALID_SOCKET) {
1546 return;
1547 }
1548
1549 struct epoll_event event = {0};
1550 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
1551 event.data.ptr = pdispatcher;
1552 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &event);
1553 RTC_DCHECK_EQ(err, 0);
1554 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001555 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_ADD";
jbauchde4db112017-05-31 13:09:18 -07001556 }
1557}
1558
1559void PhysicalSocketServer::RemoveEpoll(Dispatcher* pdispatcher) {
1560 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1561 int fd = pdispatcher->GetDescriptor();
1562 RTC_DCHECK(fd != INVALID_SOCKET);
1563 if (fd == INVALID_SOCKET) {
1564 return;
1565 }
1566
1567 struct epoll_event event = {0};
1568 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &event);
1569 RTC_DCHECK(err == 0 || errno == ENOENT);
1570 if (err == -1) {
1571 if (errno == ENOENT) {
1572 // Socket has already been closed.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001573 RTC_LOG_E(LS_VERBOSE, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001574 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001575 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001576 }
1577 }
1578}
1579
1580void PhysicalSocketServer::UpdateEpoll(Dispatcher* pdispatcher) {
1581 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1582 int fd = pdispatcher->GetDescriptor();
1583 RTC_DCHECK(fd != INVALID_SOCKET);
1584 if (fd == INVALID_SOCKET) {
1585 return;
1586 }
1587
1588 struct epoll_event event = {0};
1589 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
1590 event.data.ptr = pdispatcher;
1591 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &event);
1592 RTC_DCHECK_EQ(err, 0);
1593 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001594 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_MOD";
jbauchde4db112017-05-31 13:09:18 -07001595 }
1596}
1597
1598bool PhysicalSocketServer::WaitEpoll(int cmsWait) {
1599 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1600 int64_t tvWait = -1;
1601 int64_t tvStop = -1;
1602 if (cmsWait != kForever) {
1603 tvWait = cmsWait;
1604 tvStop = TimeAfter(cmsWait);
1605 }
1606
1607 if (epoll_events_.empty()) {
1608 // The initial space to receive events is created only if epoll is used.
1609 epoll_events_.resize(kInitialEpollEvents);
1610 }
1611
1612 fWait_ = true;
1613
1614 while (fWait_) {
1615 // Wait then call handlers as appropriate
1616 // < 0 means error
1617 // 0 means timeout
1618 // > 0 means count of descriptors ready
1619 int n = epoll_wait(epoll_fd_, &epoll_events_[0],
1620 static_cast<int>(epoll_events_.size()),
1621 static_cast<int>(tvWait));
1622 if (n < 0) {
1623 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001624 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll";
jbauchde4db112017-05-31 13:09:18 -07001625 return false;
1626 }
1627 // Else ignore the error and keep going. If this EINTR was for one of the
1628 // signals managed by this PhysicalSocketServer, the
1629 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1630 // iteration.
1631 } else if (n == 0) {
1632 // If timeout, return success
1633 return true;
1634 } else {
1635 // We have signaled descriptors
1636 CritScope cr(&crit_);
1637 for (int i = 0; i < n; ++i) {
1638 const epoll_event& event = epoll_events_[i];
1639 Dispatcher* pdispatcher = static_cast<Dispatcher*>(event.data.ptr);
1640 if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1641 // The dispatcher for this socket no longer exists.
1642 continue;
1643 }
1644
1645 bool readable = (event.events & (EPOLLIN | EPOLLPRI));
1646 bool writable = (event.events & EPOLLOUT);
1647 bool check_error = (event.events & (EPOLLRDHUP | EPOLLERR | EPOLLHUP));
1648
1649 ProcessEvents(pdispatcher, readable, writable, check_error);
1650 }
1651 }
1652
1653 if (static_cast<size_t>(n) == epoll_events_.size() &&
1654 epoll_events_.size() < kMaxEpollEvents) {
1655 // We used the complete space to receive events, increase size for future
1656 // iterations.
1657 epoll_events_.resize(std::max(epoll_events_.size() * 2, kMaxEpollEvents));
1658 }
1659
1660 if (cmsWait != kForever) {
1661 tvWait = TimeDiff(tvStop, TimeMillis());
1662 if (tvWait < 0) {
1663 // Return success on timeout.
1664 return true;
1665 }
1666 }
1667 }
1668
1669 return true;
1670}
1671
1672bool PhysicalSocketServer::WaitPoll(int cmsWait, Dispatcher* dispatcher) {
1673 RTC_DCHECK(dispatcher);
1674 int64_t tvWait = -1;
1675 int64_t tvStop = -1;
1676 if (cmsWait != kForever) {
1677 tvWait = cmsWait;
1678 tvStop = TimeAfter(cmsWait);
1679 }
1680
1681 fWait_ = true;
1682
1683 struct pollfd fds = {0};
1684 int fd = dispatcher->GetDescriptor();
1685 fds.fd = fd;
1686
1687 while (fWait_) {
1688 uint32_t ff = dispatcher->GetRequestedEvents();
1689 fds.events = 0;
1690 if (ff & (DE_READ | DE_ACCEPT)) {
1691 fds.events |= POLLIN;
1692 }
1693 if (ff & (DE_WRITE | DE_CONNECT)) {
1694 fds.events |= POLLOUT;
1695 }
1696 fds.revents = 0;
1697
1698 // Wait then call handlers as appropriate
1699 // < 0 means error
1700 // 0 means timeout
1701 // > 0 means count of descriptors ready
1702 int n = poll(&fds, 1, static_cast<int>(tvWait));
1703 if (n < 0) {
1704 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001705 RTC_LOG_E(LS_ERROR, EN, errno) << "poll";
jbauchde4db112017-05-31 13:09:18 -07001706 return false;
1707 }
1708 // Else ignore the error and keep going. If this EINTR was for one of the
1709 // signals managed by this PhysicalSocketServer, the
1710 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1711 // iteration.
1712 } else if (n == 0) {
1713 // If timeout, return success
1714 return true;
1715 } else {
1716 // We have signaled descriptors (should only be the passed dispatcher).
1717 RTC_DCHECK_EQ(n, 1);
1718 RTC_DCHECK_EQ(fds.fd, fd);
1719
1720 bool readable = (fds.revents & (POLLIN | POLLPRI));
1721 bool writable = (fds.revents & POLLOUT);
1722 bool check_error = (fds.revents & (POLLRDHUP | POLLERR | POLLHUP));
1723
1724 ProcessEvents(dispatcher, readable, writable, check_error);
1725 }
1726
1727 if (cmsWait != kForever) {
1728 tvWait = TimeDiff(tvStop, TimeMillis());
1729 if (tvWait < 0) {
1730 // Return success on timeout.
1731 return true;
1732 }
1733 }
1734 }
1735
1736 return true;
1737}
1738
1739#endif // WEBRTC_USE_EPOLL
1740
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001741static void GlobalSignalHandler(int signum) {
1742 PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
1743}
1744
1745bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
1746 void (*handler)(int)) {
1747 // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
1748 // otherwise set one.
1749 if (handler == SIG_IGN || handler == SIG_DFL) {
1750 if (!InstallSignal(signum, handler)) {
1751 return false;
1752 }
1753 if (signal_dispatcher_) {
1754 signal_dispatcher_->ClearHandler(signum);
1755 if (!signal_dispatcher_->HasHandlers()) {
1756 signal_dispatcher_.reset();
1757 }
1758 }
1759 } else {
1760 if (!signal_dispatcher_) {
1761 signal_dispatcher_.reset(new PosixSignalDispatcher(this));
1762 }
1763 signal_dispatcher_->SetHandler(signum, handler);
1764 if (!InstallSignal(signum, &GlobalSignalHandler)) {
1765 return false;
1766 }
1767 }
1768 return true;
1769}
1770
1771Dispatcher* PhysicalSocketServer::signal_dispatcher() {
1772 return signal_dispatcher_.get();
1773}
1774
1775bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
1776 struct sigaction act;
1777 // It doesn't really matter what we set this mask to.
1778 if (sigemptyset(&act.sa_mask) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001779 RTC_LOG_ERR(LS_ERROR) << "Couldn't set mask";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001780 return false;
1781 }
1782 act.sa_handler = handler;
1783#if !defined(__native_client__)
1784 // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
1785 // and it's a nuisance. Though some syscalls still return EINTR and there's no
1786 // real standard for which ones. :(
1787 act.sa_flags = SA_RESTART;
1788#else
1789 act.sa_flags = 0;
1790#endif
deadbeef37f5ecf2017-02-27 14:06:41 -08001791 if (sigaction(signum, &act, nullptr) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001792 RTC_LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001793 return false;
1794 }
1795 return true;
1796}
1797#endif // WEBRTC_POSIX
1798
1799#if defined(WEBRTC_WIN)
1800bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
Honghai Zhang82d78622016-05-06 11:29:15 -07001801 int64_t cmsTotal = cmsWait;
1802 int64_t cmsElapsed = 0;
1803 int64_t msStart = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001804
1805 fWait_ = true;
1806 while (fWait_) {
1807 std::vector<WSAEVENT> events;
Yves Gerey665174f2018-06-19 15:03:05 +02001808 std::vector<Dispatcher*> event_owners;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001809
1810 events.push_back(socket_ev_);
1811
1812 {
1813 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001814 // TODO(jbauch): Support re-entrant waiting.
1815 RTC_DCHECK(!processing_dispatchers_);
1816
1817 // Calling "CheckSignalClose" might remove a closed dispatcher from the
1818 // set. This must be deferred to prevent invalidating the iterator.
1819 processing_dispatchers_ = true;
1820 for (Dispatcher* disp : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001821 if (!process_io && (disp != signal_wakeup_))
1822 continue;
1823 SOCKET s = disp->GetSocket();
1824 if (disp->CheckSignalClose()) {
1825 // We just signalled close, don't poll this socket
1826 } else if (s != INVALID_SOCKET) {
Yves Gerey665174f2018-06-19 15:03:05 +02001827 WSAEventSelect(s, events[0],
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001828 FlagsToEvents(disp->GetRequestedEvents()));
1829 } else {
1830 events.push_back(disp->GetWSAEvent());
1831 event_owners.push_back(disp);
1832 }
1833 }
jbauchde4db112017-05-31 13:09:18 -07001834
1835 processing_dispatchers_ = false;
1836 // Process deferred dispatchers that have been added/removed while the
1837 // events were handled above.
1838 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001839 }
1840
1841 // Which is shorter, the delay wait or the asked wait?
1842
Honghai Zhang82d78622016-05-06 11:29:15 -07001843 int64_t cmsNext;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001844 if (cmsWait == kForever) {
1845 cmsNext = cmsWait;
1846 } else {
Honghai Zhang82d78622016-05-06 11:29:15 -07001847 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001848 }
1849
1850 // Wait for one of the events to signal
Yves Gerey665174f2018-06-19 15:03:05 +02001851 DWORD dw =
1852 WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()), &events[0],
1853 false, static_cast<DWORD>(cmsNext), false);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001854
1855 if (dw == WSA_WAIT_FAILED) {
1856 // Failed?
jbauch095ae152015-12-18 01:39:55 -08001857 // TODO(pthatcher): need a better strategy than this!
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001858 WSAGetLastError();
nissec80e7412017-01-11 05:56:46 -08001859 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001860 return false;
1861 } else if (dw == WSA_WAIT_TIMEOUT) {
1862 // Timeout?
1863 return true;
1864 } else {
1865 // Figure out which one it is and call it
1866 CritScope cr(&crit_);
1867 int index = dw - WSA_WAIT_EVENT_0;
1868 if (index > 0) {
Yves Gerey665174f2018-06-19 15:03:05 +02001869 --index; // The first event is the socket event
jbauchde4db112017-05-31 13:09:18 -07001870 Dispatcher* disp = event_owners[index];
1871 // The dispatcher could have been removed while waiting for events.
1872 if (dispatchers_.find(disp) != dispatchers_.end()) {
1873 disp->OnPreEvent(0);
1874 disp->OnEvent(0, 0);
1875 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001876 } else if (process_io) {
jbauchde4db112017-05-31 13:09:18 -07001877 processing_dispatchers_ = true;
1878 for (Dispatcher* disp : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001879 SOCKET s = disp->GetSocket();
1880 if (s == INVALID_SOCKET)
1881 continue;
1882
1883 WSANETWORKEVENTS wsaEvents;
1884 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1885 if (err == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001886 {
1887 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1888 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001889 RTC_LOG(WARNING)
1890 << "PhysicalSocketServer got FD_READ_BIT error "
1891 << wsaEvents.iErrorCode[FD_READ_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001892 }
1893 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1894 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001895 RTC_LOG(WARNING)
1896 << "PhysicalSocketServer got FD_WRITE_BIT error "
1897 << wsaEvents.iErrorCode[FD_WRITE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001898 }
1899 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1900 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001901 RTC_LOG(WARNING)
1902 << "PhysicalSocketServer got FD_CONNECT_BIT error "
1903 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001904 }
1905 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1906 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001907 RTC_LOG(WARNING)
1908 << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1909 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001910 }
1911 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1912 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001913 RTC_LOG(WARNING)
1914 << "PhysicalSocketServer got FD_CLOSE_BIT error "
1915 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001916 }
1917 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001918 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001919 int errcode = 0;
1920 if (wsaEvents.lNetworkEvents & FD_READ)
1921 ff |= DE_READ;
1922 if (wsaEvents.lNetworkEvents & FD_WRITE)
1923 ff |= DE_WRITE;
1924 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1925 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1926 ff |= DE_CONNECT;
1927 } else {
1928 ff |= DE_CLOSE;
1929 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1930 }
1931 }
1932 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1933 ff |= DE_ACCEPT;
1934 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1935 ff |= DE_CLOSE;
1936 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1937 }
1938 if (ff != 0) {
1939 disp->OnPreEvent(ff);
1940 disp->OnEvent(ff, errcode);
1941 }
1942 }
1943 }
jbauchde4db112017-05-31 13:09:18 -07001944
1945 processing_dispatchers_ = false;
1946 // Process deferred dispatchers that have been added/removed while the
1947 // events were handled above.
1948 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001949 }
1950
1951 // Reset the network event until new activity occurs
1952 WSAResetEvent(socket_ev_);
1953 }
1954
1955 // Break?
1956 if (!fWait_)
1957 break;
1958 cmsElapsed = TimeSince(msStart);
1959 if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
Yves Gerey665174f2018-06-19 15:03:05 +02001960 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001961 }
1962 }
1963
1964 // Done
1965 return true;
1966}
honghaizcec0a082016-01-15 14:49:09 -08001967#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001968
1969} // namespace rtc