blob: 6a23ea88fb4f64dd13be817957c7c3a1e3e88af7 [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 */
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020010#include "rtc_base/physicalsocketserver.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)
35#define WIN32_LEAN_AND_MEAN
36#include <windows.h>
37#include <winsock2.h>
38#include <ws2tcpip.h>
39#undef SetPort
40#endif
41
Patrik Höglunda8005cf2017-12-13 16:05:42 +010042#include <errno.h>
43
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000044#include <algorithm>
45#include <map>
46
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "rtc_base/arraysize.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "rtc_base/byteorder.h"
49#include "rtc_base/checks.h"
50#include "rtc_base/logging.h"
51#include "rtc_base/networkmonitor.h"
52#include "rtc_base/nullsocketserver.h"
53#include "rtc_base/timeutils.h"
54#include "rtc_base/win32socketinit.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000055
Patrik Höglunda8005cf2017-12-13 16:05:42 +010056#if defined(WEBRTC_WIN)
57#define LAST_SYSTEM_ERROR (::GetLastError())
58#elif defined(__native_client__) && __native_client__
59#define LAST_SYSTEM_ERROR (0)
60#elif defined(WEBRTC_POSIX)
61#define LAST_SYSTEM_ERROR (errno)
62#endif // WEBRTC_WIN
63
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000064#if defined(WEBRTC_POSIX)
65#include <netinet/tcp.h> // for TCP_NODELAY
Yves Gerey665174f2018-06-19 15:03:05 +020066#define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000067typedef void* SockOptArg;
Stefan Holmer9131efd2016-05-23 18:19:26 +020068
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000069#endif // WEBRTC_POSIX
70
Stefan Holmer3ebb3ef2016-05-23 20:26:11 +020071#if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) && !defined(__native_client__)
72
Stefan Holmer9131efd2016-05-23 18:19:26 +020073int64_t GetSocketRecvTimestamp(int socket) {
74 struct timeval tv_ioctl;
75 int ret = ioctl(socket, SIOCGSTAMP, &tv_ioctl);
76 if (ret != 0)
77 return -1;
78 int64_t timestamp =
79 rtc::kNumMicrosecsPerSec * static_cast<int64_t>(tv_ioctl.tv_sec) +
80 static_cast<int64_t>(tv_ioctl.tv_usec);
81 return timestamp;
82}
83
84#else
85
86int64_t GetSocketRecvTimestamp(int socket) {
87 return -1;
88}
89#endif
90
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000091#if defined(WEBRTC_WIN)
92typedef char* SockOptArg;
93#endif
94
jbauchde4db112017-05-31 13:09:18 -070095#if defined(WEBRTC_USE_EPOLL)
96// POLLRDHUP / EPOLLRDHUP are only defined starting with Linux 2.6.17.
97#if !defined(POLLRDHUP)
98#define POLLRDHUP 0x2000
99#endif
100#if !defined(EPOLLRDHUP)
101#define EPOLLRDHUP 0x2000
102#endif
103#endif
104
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000105namespace rtc {
106
danilchapbebf54c2016-04-28 01:32:48 -0700107std::unique_ptr<SocketServer> SocketServer::CreateDefault() {
108#if defined(__native_client__)
109 return std::unique_ptr<SocketServer>(new rtc::NullSocketServer);
110#else
111 return std::unique_ptr<SocketServer>(new rtc::PhysicalSocketServer);
112#endif
113}
114
jbauch095ae152015-12-18 01:39:55 -0800115PhysicalSocket::PhysicalSocket(PhysicalSocketServer* ss, SOCKET s)
Yves Gerey665174f2018-06-19 15:03:05 +0200116 : ss_(ss),
117 s_(s),
118 error_(0),
119 state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED),
120 resolver_(nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000121#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800122 // EnsureWinsockInit() ensures that winsock is initialized. The default
123 // version of this function doesn't do anything because winsock is
124 // initialized by constructor of a static object. If neccessary libjingle
125 // users can link it with a different version of this function by replacing
126 // win32socketinit.cc. See win32socketinit.cc for more details.
127 EnsureWinsockInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000128#endif
jbauch095ae152015-12-18 01:39:55 -0800129 if (s_ != INVALID_SOCKET) {
jbauch577f5dc2017-05-17 16:32:26 -0700130 SetEnabledEvents(DE_READ | DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000131
jbauch095ae152015-12-18 01:39:55 -0800132 int type = SOCK_STREAM;
133 socklen_t len = sizeof(type);
nissec16fa5e2017-02-07 07:18:43 -0800134 const int res =
135 getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len);
136 RTC_DCHECK_EQ(0, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000137 udp_ = (SOCK_DGRAM == type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000138 }
jbauch095ae152015-12-18 01:39:55 -0800139}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000140
jbauch095ae152015-12-18 01:39:55 -0800141PhysicalSocket::~PhysicalSocket() {
142 Close();
143}
144
145bool PhysicalSocket::Create(int family, int type) {
146 Close();
147 s_ = ::socket(family, type, 0);
148 udp_ = (SOCK_DGRAM == type);
149 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700150 if (udp_) {
151 SetEnabledEvents(DE_READ | DE_WRITE);
152 }
jbauch095ae152015-12-18 01:39:55 -0800153 return s_ != INVALID_SOCKET;
154}
155
156SocketAddress PhysicalSocket::GetLocalAddress() const {
157 sockaddr_storage addr_storage = {0};
158 socklen_t addrlen = sizeof(addr_storage);
159 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
160 int result = ::getsockname(s_, addr, &addrlen);
161 SocketAddress address;
162 if (result >= 0) {
163 SocketAddressFromSockAddrStorage(addr_storage, &address);
164 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100165 RTC_LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
166 << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000167 }
jbauch095ae152015-12-18 01:39:55 -0800168 return address;
169}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000170
jbauch095ae152015-12-18 01:39:55 -0800171SocketAddress PhysicalSocket::GetRemoteAddress() const {
172 sockaddr_storage addr_storage = {0};
173 socklen_t addrlen = sizeof(addr_storage);
174 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
175 int result = ::getpeername(s_, addr, &addrlen);
176 SocketAddress address;
177 if (result >= 0) {
178 SocketAddressFromSockAddrStorage(addr_storage, &address);
179 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100180 RTC_LOG(LS_WARNING)
181 << "GetRemoteAddress: unable to get remote addr, socket=" << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000182 }
jbauch095ae152015-12-18 01:39:55 -0800183 return address;
184}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000185
jbauch095ae152015-12-18 01:39:55 -0800186int PhysicalSocket::Bind(const SocketAddress& bind_addr) {
deadbeefc874d122017-02-13 15:41:59 -0800187 SocketAddress copied_bind_addr = bind_addr;
188 // If a network binder is available, use it to bind a socket to an interface
189 // instead of bind(), since this is more reliable on an OS with a weak host
190 // model.
deadbeef9ffa13f2017-02-21 16:18:00 -0800191 if (ss_->network_binder() && !bind_addr.IsAnyIP()) {
deadbeefc874d122017-02-13 15:41:59 -0800192 NetworkBindingResult result =
193 ss_->network_binder()->BindSocketToNetwork(s_, bind_addr.ipaddr());
194 if (result == NetworkBindingResult::SUCCESS) {
195 // Since the network binder handled binding the socket to the desired
196 // network interface, we don't need to (and shouldn't) include an IP in
197 // the bind() call; bind() just needs to assign a port.
198 copied_bind_addr.SetIP(GetAnyIP(copied_bind_addr.ipaddr().family()));
199 } else if (result == NetworkBindingResult::NOT_IMPLEMENTED) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100200 RTC_LOG(LS_INFO) << "Can't bind socket to network because "
201 "network binding is not implemented for this OS.";
deadbeefc874d122017-02-13 15:41:59 -0800202 } else {
203 if (bind_addr.IsLoopbackIP()) {
204 // If we couldn't bind to a loopback IP (which should only happen in
205 // test scenarios), continue on. This may be expected behavior.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100206 RTC_LOG(LS_VERBOSE) << "Binding socket to loopback address "
207 << bind_addr.ipaddr().ToString()
208 << " failed; result: " << static_cast<int>(result);
deadbeefc874d122017-02-13 15:41:59 -0800209 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100210 RTC_LOG(LS_WARNING) << "Binding socket to network address "
211 << bind_addr.ipaddr().ToString()
212 << " failed; result: " << static_cast<int>(result);
deadbeefc874d122017-02-13 15:41:59 -0800213 // If a network binding was attempted and failed, we should stop here
214 // and not try to use the socket. Otherwise, we may end up sending
215 // packets with an invalid source address.
216 // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=7026
217 return -1;
218 }
219 }
220 }
jbauch095ae152015-12-18 01:39:55 -0800221 sockaddr_storage addr_storage;
deadbeefc874d122017-02-13 15:41:59 -0800222 size_t len = copied_bind_addr.ToSockAddrStorage(&addr_storage);
jbauch095ae152015-12-18 01:39:55 -0800223 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
224 int err = ::bind(s_, addr, static_cast<int>(len));
225 UpdateLastError();
tfarinaa41ab932015-10-30 16:08:48 -0700226#if !defined(NDEBUG)
jbauch095ae152015-12-18 01:39:55 -0800227 if (0 == err) {
228 dbg_addr_ = "Bound @ ";
229 dbg_addr_.append(GetLocalAddress().ToString());
230 }
tfarinaa41ab932015-10-30 16:08:48 -0700231#endif
jbauch095ae152015-12-18 01:39:55 -0800232 return err;
233}
234
235int PhysicalSocket::Connect(const SocketAddress& addr) {
236 // TODO(pthatcher): Implicit creation is required to reconnect...
237 // ...but should we make it more explicit?
238 if (state_ != CS_CLOSED) {
239 SetError(EALREADY);
240 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000241 }
jbauch095ae152015-12-18 01:39:55 -0800242 if (addr.IsUnresolvedIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100243 RTC_LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
jbauch095ae152015-12-18 01:39:55 -0800244 resolver_ = new AsyncResolver();
245 resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult);
246 resolver_->Start(addr);
247 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000248 return 0;
249 }
250
jbauch095ae152015-12-18 01:39:55 -0800251 return DoConnect(addr);
252}
253
254int PhysicalSocket::DoConnect(const SocketAddress& connect_addr) {
Yves Gerey665174f2018-06-19 15:03:05 +0200255 if ((s_ == INVALID_SOCKET) && !Create(connect_addr.family(), SOCK_STREAM)) {
jbauch095ae152015-12-18 01:39:55 -0800256 return SOCKET_ERROR;
257 }
258 sockaddr_storage addr_storage;
259 size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
260 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
261 int err = ::connect(s_, addr, static_cast<int>(len));
262 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700263 uint8_t events = DE_READ | DE_WRITE;
jbauch095ae152015-12-18 01:39:55 -0800264 if (err == 0) {
265 state_ = CS_CONNECTED;
266 } else if (IsBlockingError(GetError())) {
267 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700268 events |= DE_CONNECT;
jbauch095ae152015-12-18 01:39:55 -0800269 } else {
270 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000271 }
272
jbauch577f5dc2017-05-17 16:32:26 -0700273 EnableEvents(events);
jbauch095ae152015-12-18 01:39:55 -0800274 return 0;
275}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000276
jbauch095ae152015-12-18 01:39:55 -0800277int PhysicalSocket::GetError() const {
278 CritScope cs(&crit_);
279 return error_;
280}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000281
jbauch095ae152015-12-18 01:39:55 -0800282void PhysicalSocket::SetError(int error) {
283 CritScope cs(&crit_);
284 error_ = error;
285}
286
287AsyncSocket::ConnState PhysicalSocket::GetState() const {
288 return state_;
289}
290
291int PhysicalSocket::GetOption(Option opt, int* value) {
292 int slevel;
293 int sopt;
294 if (TranslateOption(opt, &slevel, &sopt) == -1)
295 return -1;
296 socklen_t optlen = sizeof(*value);
297 int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
298 if (ret != -1 && opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000299#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800300 *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000301#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000302 }
jbauch095ae152015-12-18 01:39:55 -0800303 return ret;
304}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000305
jbauch095ae152015-12-18 01:39:55 -0800306int PhysicalSocket::SetOption(Option opt, int value) {
307 int slevel;
308 int sopt;
309 if (TranslateOption(opt, &slevel, &sopt) == -1)
310 return -1;
311 if (opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000312#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800313 value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000314#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000315 }
jbauch095ae152015-12-18 01:39:55 -0800316 return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
317}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000318
jbauch095ae152015-12-18 01:39:55 -0800319int PhysicalSocket::Send(const void* pv, size_t cb) {
Yves Gerey665174f2018-06-19 15:03:05 +0200320 int sent = DoSend(
321 s_, reinterpret_cast<const char*>(pv), static_cast<int>(cb),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000322#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800323 // Suppress SIGPIPE. Without this, attempting to send on a socket whose
324 // other end is closed will result in a SIGPIPE signal being raised to
325 // our process, which by default will terminate the process, which we
326 // don't want. By specifying this flag, we'll just get the error EPIPE
327 // instead and can handle the error gracefully.
328 MSG_NOSIGNAL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000329#else
jbauch095ae152015-12-18 01:39:55 -0800330 0
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000331#endif
jbauch095ae152015-12-18 01:39:55 -0800332 );
333 UpdateLastError();
334 MaybeRemapSendError();
335 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800336 RTC_DCHECK(sent <= static_cast<int>(cb));
jbauchf2a2bf42016-02-03 16:45:32 -0800337 if ((sent > 0 && sent < static_cast<int>(cb)) ||
338 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700339 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000340 }
jbauch095ae152015-12-18 01:39:55 -0800341 return sent;
342}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000343
jbauch095ae152015-12-18 01:39:55 -0800344int PhysicalSocket::SendTo(const void* buffer,
345 size_t length,
346 const SocketAddress& addr) {
347 sockaddr_storage saddr;
348 size_t len = addr.ToSockAddrStorage(&saddr);
Yves Gerey665174f2018-06-19 15:03:05 +0200349 int sent =
350 DoSendTo(s_, static_cast<const char*>(buffer), static_cast<int>(length),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000351#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
Yves Gerey665174f2018-06-19 15:03:05 +0200352 // Suppress SIGPIPE. See above for explanation.
353 MSG_NOSIGNAL,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000354#else
Yves Gerey665174f2018-06-19 15:03:05 +0200355 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000356#endif
Yves Gerey665174f2018-06-19 15:03:05 +0200357 reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
jbauch095ae152015-12-18 01:39:55 -0800358 UpdateLastError();
359 MaybeRemapSendError();
360 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800361 RTC_DCHECK(sent <= static_cast<int>(length));
jbauchf2a2bf42016-02-03 16:45:32 -0800362 if ((sent > 0 && sent < static_cast<int>(length)) ||
363 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700364 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000365 }
jbauch095ae152015-12-18 01:39:55 -0800366 return sent;
367}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000368
Stefan Holmer9131efd2016-05-23 18:19:26 +0200369int PhysicalSocket::Recv(void* buffer, size_t length, int64_t* timestamp) {
Yves Gerey665174f2018-06-19 15:03:05 +0200370 int received =
371 ::recv(s_, static_cast<char*>(buffer), static_cast<int>(length), 0);
jbauch095ae152015-12-18 01:39:55 -0800372 if ((received == 0) && (length != 0)) {
373 // Note: on graceful shutdown, recv can return 0. In this case, we
374 // pretend it is blocking, and then signal close, so that simplifying
375 // assumptions can be made about Recv.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100376 RTC_LOG(LS_WARNING) << "EOF from socket; deferring close event";
jbauch095ae152015-12-18 01:39:55 -0800377 // Must turn this back on so that the select() loop will notice the close
378 // event.
jbauch577f5dc2017-05-17 16:32:26 -0700379 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800380 SetError(EWOULDBLOCK);
381 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000382 }
Stefan Holmer9131efd2016-05-23 18:19:26 +0200383 if (timestamp) {
384 *timestamp = GetSocketRecvTimestamp(s_);
385 }
jbauch095ae152015-12-18 01:39:55 -0800386 UpdateLastError();
387 int error = GetError();
388 bool success = (received >= 0) || IsBlockingError(error);
389 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700390 EnableEvents(DE_READ);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000391 }
jbauch095ae152015-12-18 01:39:55 -0800392 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100393 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000394 }
jbauch095ae152015-12-18 01:39:55 -0800395 return received;
396}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000397
jbauch095ae152015-12-18 01:39:55 -0800398int PhysicalSocket::RecvFrom(void* buffer,
399 size_t length,
Stefan Holmer9131efd2016-05-23 18:19:26 +0200400 SocketAddress* out_addr,
401 int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800402 sockaddr_storage addr_storage;
403 socklen_t addr_len = sizeof(addr_storage);
404 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
405 int received = ::recvfrom(s_, static_cast<char*>(buffer),
406 static_cast<int>(length), 0, addr, &addr_len);
Stefan Holmer9131efd2016-05-23 18:19:26 +0200407 if (timestamp) {
408 *timestamp = GetSocketRecvTimestamp(s_);
409 }
jbauch095ae152015-12-18 01:39:55 -0800410 UpdateLastError();
411 if ((received >= 0) && (out_addr != nullptr))
412 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
413 int error = GetError();
414 bool success = (received >= 0) || IsBlockingError(error);
415 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700416 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800417 }
418 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100419 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
jbauch095ae152015-12-18 01:39:55 -0800420 }
421 return received;
422}
423
424int PhysicalSocket::Listen(int backlog) {
425 int err = ::listen(s_, backlog);
426 UpdateLastError();
427 if (err == 0) {
428 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700429 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800430#if !defined(NDEBUG)
431 dbg_addr_ = "Listening @ ";
432 dbg_addr_.append(GetLocalAddress().ToString());
433#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000434 }
jbauch095ae152015-12-18 01:39:55 -0800435 return err;
436}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000437
jbauch095ae152015-12-18 01:39:55 -0800438AsyncSocket* PhysicalSocket::Accept(SocketAddress* out_addr) {
439 // Always re-subscribe DE_ACCEPT to make sure new incoming connections will
440 // trigger an event even if DoAccept returns an error here.
jbauch577f5dc2017-05-17 16:32:26 -0700441 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800442 sockaddr_storage addr_storage;
443 socklen_t addr_len = sizeof(addr_storage);
444 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
445 SOCKET s = DoAccept(s_, addr, &addr_len);
446 UpdateLastError();
447 if (s == INVALID_SOCKET)
448 return nullptr;
449 if (out_addr != nullptr)
450 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
451 return ss_->WrapSocket(s);
452}
453
454int PhysicalSocket::Close() {
455 if (s_ == INVALID_SOCKET)
456 return 0;
457 int err = ::closesocket(s_);
458 UpdateLastError();
459 s_ = INVALID_SOCKET;
460 state_ = CS_CLOSED;
jbauch577f5dc2017-05-17 16:32:26 -0700461 SetEnabledEvents(0);
jbauch095ae152015-12-18 01:39:55 -0800462 if (resolver_) {
463 resolver_->Destroy(false);
464 resolver_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000465 }
jbauch095ae152015-12-18 01:39:55 -0800466 return err;
467}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000468
jbauch095ae152015-12-18 01:39:55 -0800469SOCKET PhysicalSocket::DoAccept(SOCKET socket,
470 sockaddr* addr,
471 socklen_t* addrlen) {
472 return ::accept(socket, addr, addrlen);
473}
474
jbauchf2a2bf42016-02-03 16:45:32 -0800475int PhysicalSocket::DoSend(SOCKET socket, const char* buf, int len, int flags) {
476 return ::send(socket, buf, len, flags);
477}
478
479int PhysicalSocket::DoSendTo(SOCKET socket,
480 const char* buf,
481 int len,
482 int flags,
483 const struct sockaddr* dest_addr,
484 socklen_t addrlen) {
485 return ::sendto(socket, buf, len, flags, dest_addr, addrlen);
486}
487
jbauch095ae152015-12-18 01:39:55 -0800488void PhysicalSocket::OnResolveResult(AsyncResolverInterface* resolver) {
489 if (resolver != resolver_) {
490 return;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000491 }
492
jbauch095ae152015-12-18 01:39:55 -0800493 int error = resolver_->GetError();
494 if (error == 0) {
495 error = DoConnect(resolver_->address());
496 } else {
497 Close();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000498 }
499
jbauch095ae152015-12-18 01:39:55 -0800500 if (error) {
501 SetError(error);
502 SignalCloseEvent(this, error);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000503 }
jbauch095ae152015-12-18 01:39:55 -0800504}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000505
jbauch095ae152015-12-18 01:39:55 -0800506void PhysicalSocket::UpdateLastError() {
Patrik Höglunda8005cf2017-12-13 16:05:42 +0100507 SetError(LAST_SYSTEM_ERROR);
jbauch095ae152015-12-18 01:39:55 -0800508}
509
510void PhysicalSocket::MaybeRemapSendError() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000511#if defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800512 // https://developer.apple.com/library/mac/documentation/Darwin/
513 // Reference/ManPages/man2/sendto.2.html
514 // ENOBUFS - The output queue for a network interface is full.
515 // This generally indicates that the interface has stopped sending,
516 // but may be caused by transient congestion.
517 if (GetError() == ENOBUFS) {
518 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000519 }
jbauch095ae152015-12-18 01:39:55 -0800520#endif
521}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000522
jbauch577f5dc2017-05-17 16:32:26 -0700523void PhysicalSocket::SetEnabledEvents(uint8_t events) {
524 enabled_events_ = events;
525}
526
527void PhysicalSocket::EnableEvents(uint8_t events) {
528 enabled_events_ |= events;
529}
530
531void PhysicalSocket::DisableEvents(uint8_t events) {
532 enabled_events_ &= ~events;
533}
534
jbauch095ae152015-12-18 01:39:55 -0800535int PhysicalSocket::TranslateOption(Option opt, int* slevel, int* sopt) {
536 switch (opt) {
537 case OPT_DONTFRAGMENT:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000538#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800539 *slevel = IPPROTO_IP;
540 *sopt = IP_DONTFRAGMENT;
541 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000542#elif defined(WEBRTC_MAC) || defined(BSD) || defined(__native_client__)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100543 RTC_LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
jbauch095ae152015-12-18 01:39:55 -0800544 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000545#elif defined(WEBRTC_POSIX)
jbauch095ae152015-12-18 01:39:55 -0800546 *slevel = IPPROTO_IP;
547 *sopt = IP_MTU_DISCOVER;
548 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000549#endif
jbauch095ae152015-12-18 01:39:55 -0800550 case OPT_RCVBUF:
551 *slevel = SOL_SOCKET;
552 *sopt = SO_RCVBUF;
553 break;
554 case OPT_SNDBUF:
555 *slevel = SOL_SOCKET;
556 *sopt = SO_SNDBUF;
557 break;
558 case OPT_NODELAY:
559 *slevel = IPPROTO_TCP;
560 *sopt = TCP_NODELAY;
561 break;
562 case OPT_DSCP:
Mirko Bonadei675513b2017-11-09 11:09:25 +0100563 RTC_LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
jbauch095ae152015-12-18 01:39:55 -0800564 return -1;
565 case OPT_RTP_SENDTIME_EXTN_ID:
566 return -1; // No logging is necessary as this not a OS socket option.
567 default:
nissec80e7412017-01-11 05:56:46 -0800568 RTC_NOTREACHED();
jbauch095ae152015-12-18 01:39:55 -0800569 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000570 }
jbauch095ae152015-12-18 01:39:55 -0800571 return 0;
572}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000573
Yves Gerey665174f2018-06-19 15:03:05 +0200574SocketDispatcher::SocketDispatcher(PhysicalSocketServer* ss)
jbauch4331fcd2016-01-06 22:20:28 -0800575#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200576 : PhysicalSocket(ss),
577 id_(0),
578 signal_close_(false)
jbauch4331fcd2016-01-06 22:20:28 -0800579#else
Yves Gerey665174f2018-06-19 15:03:05 +0200580 : PhysicalSocket(ss)
jbauch4331fcd2016-01-06 22:20:28 -0800581#endif
582{
583}
584
Yves Gerey665174f2018-06-19 15:03:05 +0200585SocketDispatcher::SocketDispatcher(SOCKET s, PhysicalSocketServer* ss)
jbauch4331fcd2016-01-06 22:20:28 -0800586#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200587 : PhysicalSocket(ss, s),
588 id_(0),
589 signal_close_(false)
jbauch4331fcd2016-01-06 22:20:28 -0800590#else
Yves Gerey665174f2018-06-19 15:03:05 +0200591 : PhysicalSocket(ss, s)
jbauch4331fcd2016-01-06 22:20:28 -0800592#endif
593{
594}
595
596SocketDispatcher::~SocketDispatcher() {
597 Close();
598}
599
600bool SocketDispatcher::Initialize() {
nisseede5da42017-01-12 05:15:36 -0800601 RTC_DCHECK(s_ != INVALID_SOCKET);
Yves Gerey665174f2018-06-19 15:03:05 +0200602// Must be a non-blocking
jbauch4331fcd2016-01-06 22:20:28 -0800603#if defined(WEBRTC_WIN)
604 u_long argp = 1;
605 ioctlsocket(s_, FIONBIO, &argp);
606#elif defined(WEBRTC_POSIX)
607 fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
608#endif
deadbeefeae45642017-05-26 16:27:09 -0700609#if defined(WEBRTC_IOS)
610 // iOS may kill sockets when the app is moved to the background
611 // (specifically, if the app doesn't use the "voip" UIBackgroundMode). When
612 // we attempt to write to such a socket, SIGPIPE will be raised, which by
613 // default will terminate the process, which we don't want. By specifying
614 // this socket option, SIGPIPE will be disabled for the socket.
615 int value = 1;
616 ::setsockopt(s_, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value));
617#endif
jbauch4331fcd2016-01-06 22:20:28 -0800618 ss_->Add(this);
619 return true;
620}
621
622bool SocketDispatcher::Create(int type) {
623 return Create(AF_INET, type);
624}
625
626bool SocketDispatcher::Create(int family, int type) {
627 // Change the socket to be non-blocking.
628 if (!PhysicalSocket::Create(family, type))
629 return false;
630
631 if (!Initialize())
632 return false;
633
634#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200635 do {
636 id_ = ++next_id_;
637 } while (id_ == 0);
jbauch4331fcd2016-01-06 22:20:28 -0800638#endif
639 return true;
640}
641
642#if defined(WEBRTC_WIN)
643
644WSAEVENT SocketDispatcher::GetWSAEvent() {
645 return WSA_INVALID_EVENT;
646}
647
648SOCKET SocketDispatcher::GetSocket() {
649 return s_;
650}
651
652bool SocketDispatcher::CheckSignalClose() {
653 if (!signal_close_)
654 return false;
655
656 char ch;
657 if (recv(s_, &ch, 1, MSG_PEEK) > 0)
658 return false;
659
660 state_ = CS_CLOSED;
661 signal_close_ = false;
662 SignalCloseEvent(this, signal_err_);
663 return true;
664}
665
666int SocketDispatcher::next_id_ = 0;
667
668#elif defined(WEBRTC_POSIX)
669
670int SocketDispatcher::GetDescriptor() {
671 return s_;
672}
673
674bool SocketDispatcher::IsDescriptorClosed() {
deadbeeffaedf7f2017-02-09 15:09:22 -0800675 if (udp_) {
676 // The MSG_PEEK trick doesn't work for UDP, since (at least in some
677 // circumstances) it requires reading an entire UDP packet, which would be
678 // bad for performance here. So, just check whether |s_| has been closed,
679 // which should be sufficient.
680 return s_ == INVALID_SOCKET;
681 }
jbauch4331fcd2016-01-06 22:20:28 -0800682 // We don't have a reliable way of distinguishing end-of-stream
683 // from readability. So test on each readable call. Is this
684 // inefficient? Probably.
685 char ch;
686 ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
687 if (res > 0) {
688 // Data available, so not closed.
689 return false;
690 } else if (res == 0) {
691 // EOF, so closed.
692 return true;
693 } else { // error
694 switch (errno) {
695 // Returned if we've already closed s_.
696 case EBADF:
697 // Returned during ungraceful peer shutdown.
698 case ECONNRESET:
699 return true;
deadbeeffaedf7f2017-02-09 15:09:22 -0800700 // The normal blocking error; don't log anything.
701 case EWOULDBLOCK:
702 // Interrupted system call.
703 case EINTR:
704 return false;
jbauch4331fcd2016-01-06 22:20:28 -0800705 default:
706 // Assume that all other errors are just blocking errors, meaning the
707 // connection is still good but we just can't read from it right now.
708 // This should only happen when connecting (and at most once), because
709 // in all other cases this function is only called if the file
710 // descriptor is already known to be in the readable state. However,
711 // it's not necessary a problem if we spuriously interpret a
712 // "connection lost"-type error as a blocking error, because typically
713 // the next recv() will get EOF, so we'll still eventually notice that
714 // the socket is closed.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100715 RTC_LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
jbauch4331fcd2016-01-06 22:20:28 -0800716 return false;
717 }
718 }
719}
720
Yves Gerey665174f2018-06-19 15:03:05 +0200721#endif // WEBRTC_POSIX
jbauch4331fcd2016-01-06 22:20:28 -0800722
723uint32_t SocketDispatcher::GetRequestedEvents() {
jbauch577f5dc2017-05-17 16:32:26 -0700724 return enabled_events();
jbauch4331fcd2016-01-06 22:20:28 -0800725}
726
727void SocketDispatcher::OnPreEvent(uint32_t ff) {
728 if ((ff & DE_CONNECT) != 0)
729 state_ = CS_CONNECTED;
730
731#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200732// We set CS_CLOSED from CheckSignalClose.
jbauch4331fcd2016-01-06 22:20:28 -0800733#elif defined(WEBRTC_POSIX)
734 if ((ff & DE_CLOSE) != 0)
735 state_ = CS_CLOSED;
736#endif
737}
738
739#if defined(WEBRTC_WIN)
740
741void SocketDispatcher::OnEvent(uint32_t ff, int err) {
742 int cache_id = id_;
743 // Make sure we deliver connect/accept first. Otherwise, consumers may see
744 // something like a READ followed by a CONNECT, which would be odd.
745 if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
746 if (ff != DE_CONNECT)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100747 RTC_LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
jbauch577f5dc2017-05-17 16:32:26 -0700748 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800749#if !defined(NDEBUG)
750 dbg_addr_ = "Connected @ ";
751 dbg_addr_.append(GetRemoteAddress().ToString());
752#endif
753 SignalConnectEvent(this);
754 }
755 if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700756 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800757 SignalReadEvent(this);
758 }
759 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700760 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800761 SignalReadEvent(this);
762 }
763 if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700764 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800765 SignalWriteEvent(this);
766 }
767 if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
768 signal_close_ = true;
769 signal_err_ = err;
770 }
771}
772
773#elif defined(WEBRTC_POSIX)
774
775void SocketDispatcher::OnEvent(uint32_t ff, int err) {
jbauchde4db112017-05-31 13:09:18 -0700776#if defined(WEBRTC_USE_EPOLL)
777 // Remember currently enabled events so we can combine multiple changes
778 // into one update call later.
779 // The signal handlers might re-enable events disabled here, so we can't
780 // keep a list of events to disable at the end of the method. This list
781 // would not be updated with the events enabled by the signal handlers.
782 StartBatchedEventUpdates();
783#endif
jbauch4331fcd2016-01-06 22:20:28 -0800784 // Make sure we deliver connect/accept first. Otherwise, consumers may see
785 // something like a READ followed by a CONNECT, which would be odd.
786 if ((ff & DE_CONNECT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700787 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800788 SignalConnectEvent(this);
789 }
790 if ((ff & DE_ACCEPT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700791 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800792 SignalReadEvent(this);
793 }
794 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700795 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800796 SignalReadEvent(this);
797 }
798 if ((ff & DE_WRITE) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700799 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800800 SignalWriteEvent(this);
801 }
802 if ((ff & DE_CLOSE) != 0) {
803 // The socket is now dead to us, so stop checking it.
jbauch577f5dc2017-05-17 16:32:26 -0700804 SetEnabledEvents(0);
jbauch4331fcd2016-01-06 22:20:28 -0800805 SignalCloseEvent(this, err);
806 }
jbauchde4db112017-05-31 13:09:18 -0700807#if defined(WEBRTC_USE_EPOLL)
808 FinishBatchedEventUpdates();
809#endif
jbauch4331fcd2016-01-06 22:20:28 -0800810}
811
Yves Gerey665174f2018-06-19 15:03:05 +0200812#endif // WEBRTC_POSIX
jbauch4331fcd2016-01-06 22:20:28 -0800813
jbauchde4db112017-05-31 13:09:18 -0700814#if defined(WEBRTC_USE_EPOLL)
815
816static int GetEpollEvents(uint32_t ff) {
817 int events = 0;
818 if (ff & (DE_READ | DE_ACCEPT)) {
819 events |= EPOLLIN;
820 }
821 if (ff & (DE_WRITE | DE_CONNECT)) {
822 events |= EPOLLOUT;
823 }
824 return events;
825}
826
827void SocketDispatcher::StartBatchedEventUpdates() {
828 RTC_DCHECK_EQ(saved_enabled_events_, -1);
829 saved_enabled_events_ = enabled_events();
830}
831
832void SocketDispatcher::FinishBatchedEventUpdates() {
833 RTC_DCHECK_NE(saved_enabled_events_, -1);
834 uint8_t old_events = static_cast<uint8_t>(saved_enabled_events_);
835 saved_enabled_events_ = -1;
836 MaybeUpdateDispatcher(old_events);
837}
838
839void SocketDispatcher::MaybeUpdateDispatcher(uint8_t old_events) {
840 if (GetEpollEvents(enabled_events()) != GetEpollEvents(old_events) &&
841 saved_enabled_events_ == -1) {
842 ss_->Update(this);
843 }
844}
845
846void SocketDispatcher::SetEnabledEvents(uint8_t events) {
847 uint8_t old_events = enabled_events();
848 PhysicalSocket::SetEnabledEvents(events);
849 MaybeUpdateDispatcher(old_events);
850}
851
852void SocketDispatcher::EnableEvents(uint8_t events) {
853 uint8_t old_events = enabled_events();
854 PhysicalSocket::EnableEvents(events);
855 MaybeUpdateDispatcher(old_events);
856}
857
858void SocketDispatcher::DisableEvents(uint8_t events) {
859 uint8_t old_events = enabled_events();
860 PhysicalSocket::DisableEvents(events);
861 MaybeUpdateDispatcher(old_events);
862}
863
864#endif // WEBRTC_USE_EPOLL
865
jbauch4331fcd2016-01-06 22:20:28 -0800866int SocketDispatcher::Close() {
867 if (s_ == INVALID_SOCKET)
868 return 0;
869
870#if defined(WEBRTC_WIN)
871 id_ = 0;
872 signal_close_ = false;
873#endif
874 ss_->Remove(this);
875 return PhysicalSocket::Close();
876}
877
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000878#if defined(WEBRTC_POSIX)
879class EventDispatcher : public Dispatcher {
880 public:
881 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
882 if (pipe(afd_) < 0)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100883 RTC_LOG(LERROR) << "pipe failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000884 ss_->Add(this);
885 }
886
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000887 ~EventDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000888 ss_->Remove(this);
889 close(afd_[0]);
890 close(afd_[1]);
891 }
892
893 virtual void Signal() {
894 CritScope cs(&crit_);
895 if (!fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200896 const uint8_t b[1] = {0};
nissec16fa5e2017-02-07 07:18:43 -0800897 const ssize_t res = write(afd_[1], b, sizeof(b));
898 RTC_DCHECK_EQ(1, res);
899 fSignaled_ = true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000900 }
901 }
902
Peter Boström0c4e06b2015-10-07 12:23:21 +0200903 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000904
Peter Boström0c4e06b2015-10-07 12:23:21 +0200905 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000906 // It is not possible to perfectly emulate an auto-resetting event with
907 // pipes. This simulates it by resetting before the event is handled.
908
909 CritScope cs(&crit_);
910 if (fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200911 uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
nissec16fa5e2017-02-07 07:18:43 -0800912 const ssize_t res = read(afd_[0], b, sizeof(b));
913 RTC_DCHECK_EQ(1, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000914 fSignaled_ = false;
915 }
916 }
917
nissec80e7412017-01-11 05:56:46 -0800918 void OnEvent(uint32_t ff, int err) override { RTC_NOTREACHED(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000919
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000920 int GetDescriptor() override { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000921
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000922 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000923
924 private:
Yves Gerey665174f2018-06-19 15:03:05 +0200925 PhysicalSocketServer* ss_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000926 int afd_[2];
927 bool fSignaled_;
928 CriticalSection crit_;
929};
930
931// These two classes use the self-pipe trick to deliver POSIX signals to our
932// select loop. This is the only safe, reliable, cross-platform way to do
933// non-trivial things with a POSIX signal in an event-driven program (until
934// proper pselect() implementations become ubiquitous).
935
936class PosixSignalHandler {
937 public:
938 // POSIX only specifies 32 signals, but in principle the system might have
939 // more and the programmer might choose to use them, so we size our array
940 // for 128.
941 static const int kNumPosixSignals = 128;
942
943 // There is just a single global instance. (Signal handlers do not get any
944 // sort of user-defined void * parameter, so they can't access anything that
945 // isn't global.)
946 static PosixSignalHandler* Instance() {
Niels Möller14682a32018-05-24 08:54:25 +0200947 static PosixSignalHandler* const instance = new PosixSignalHandler();
948 return instance;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000949 }
950
951 // Returns true if the given signal number is set.
952 bool IsSignalSet(int signum) const {
nisseede5da42017-01-12 05:15:36 -0800953 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800954 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000955 return received_signal_[signum];
956 } else {
957 return false;
958 }
959 }
960
961 // Clears the given signal number.
962 void ClearSignal(int signum) {
nisseede5da42017-01-12 05:15:36 -0800963 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800964 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000965 received_signal_[signum] = false;
966 }
967 }
968
969 // Returns the file descriptor to monitor for signal events.
Yves Gerey665174f2018-06-19 15:03:05 +0200970 int GetDescriptor() const { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000971
972 // This is called directly from our real signal handler, so it must be
973 // signal-handler-safe. That means it cannot assume anything about the
974 // user-level state of the process, since the handler could be executed at any
975 // time on any thread.
976 void OnPosixSignalReceived(int signum) {
tfarina5237aaf2015-11-10 23:44:30 -0800977 if (signum >= static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000978 // We don't have space in our array for this.
979 return;
980 }
981 // Set a flag saying we've seen this signal.
982 received_signal_[signum] = true;
983 // Notify application code that we got a signal.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200984 const uint8_t b[1] = {0};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000985 if (-1 == write(afd_[1], b, sizeof(b))) {
986 // Nothing we can do here. If there's an error somehow then there's
987 // nothing we can safely do from a signal handler.
988 // No, we can't even safely log it.
989 // But, we still have to check the return value here. Otherwise,
990 // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
991 return;
992 }
993 }
994
995 private:
996 PosixSignalHandler() {
997 if (pipe(afd_) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100998 RTC_LOG_ERR(LS_ERROR) << "pipe failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000999 return;
1000 }
1001 if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001002 RTC_LOG_ERR(LS_WARNING) << "fcntl #1 failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001003 }
1004 if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001005 RTC_LOG_ERR(LS_WARNING) << "fcntl #2 failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001006 }
Yves Gerey665174f2018-06-19 15:03:05 +02001007 memset(const_cast<void*>(static_cast<volatile void*>(received_signal_)), 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001008 sizeof(received_signal_));
1009 }
1010
1011 ~PosixSignalHandler() {
1012 int fd1 = afd_[0];
1013 int fd2 = afd_[1];
1014 // We clobber the stored file descriptor numbers here or else in principle
1015 // a signal that happens to be delivered during application termination
1016 // could erroneously write a zero byte to an unrelated file handle in
1017 // OnPosixSignalReceived() if some other file happens to be opened later
1018 // during shutdown and happens to be given the same file descriptor number
1019 // as our pipe had. Unfortunately even with this precaution there is still a
1020 // race where that could occur if said signal happens to be handled
1021 // concurrently with this code and happens to have already read the value of
1022 // afd_[1] from memory before we clobber it, but that's unlikely.
1023 afd_[0] = -1;
1024 afd_[1] = -1;
1025 close(fd1);
1026 close(fd2);
1027 }
1028
1029 int afd_[2];
1030 // These are boolean flags that will be set in our signal handler and read
1031 // and cleared from Wait(). There is a race involved in this, but it is
1032 // benign. The signal handler sets the flag before signaling the pipe, so
1033 // we'll never end up blocking in select() while a flag is still true.
1034 // However, if two of the same signal arrive close to each other then it's
1035 // possible that the second time the handler may set the flag while it's still
1036 // true, meaning that signal will be missed. But the first occurrence of it
1037 // will still be handled, so this isn't a problem.
1038 // Volatile is not necessary here for correctness, but this data _is_ volatile
1039 // so I've marked it as such.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001040 volatile uint8_t received_signal_[kNumPosixSignals];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001041};
1042
1043class PosixSignalDispatcher : public Dispatcher {
1044 public:
Yves Gerey665174f2018-06-19 15:03:05 +02001045 PosixSignalDispatcher(PhysicalSocketServer* owner) : owner_(owner) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001046 owner_->Add(this);
1047 }
1048
Yves Gerey665174f2018-06-19 15:03:05 +02001049 ~PosixSignalDispatcher() override { owner_->Remove(this); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001050
Peter Boström0c4e06b2015-10-07 12:23:21 +02001051 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001052
Peter Boström0c4e06b2015-10-07 12:23:21 +02001053 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001054 // Events might get grouped if signals come very fast, so we read out up to
1055 // 16 bytes to make sure we keep the pipe empty.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001056 uint8_t b[16];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001057 ssize_t ret = read(GetDescriptor(), b, sizeof(b));
1058 if (ret < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001059 RTC_LOG_ERR(LS_WARNING) << "Error in read()";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001060 } else if (ret == 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001061 RTC_LOG(LS_WARNING) << "Should have read at least one byte";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001062 }
1063 }
1064
Peter Boström0c4e06b2015-10-07 12:23:21 +02001065 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001066 for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
1067 ++signum) {
1068 if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
1069 PosixSignalHandler::Instance()->ClearSignal(signum);
1070 HandlerMap::iterator i = handlers_.find(signum);
1071 if (i == handlers_.end()) {
1072 // This can happen if a signal is delivered to our process at around
1073 // the same time as we unset our handler for it. It is not an error
1074 // condition, but it's unusual enough to be worth logging.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001075 RTC_LOG(LS_INFO) << "Received signal with no handler: " << signum;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001076 } else {
1077 // Otherwise, execute our handler.
1078 (*i->second)(signum);
1079 }
1080 }
1081 }
1082 }
1083
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001084 int GetDescriptor() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001085 return PosixSignalHandler::Instance()->GetDescriptor();
1086 }
1087
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001088 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001089
1090 void SetHandler(int signum, void (*handler)(int)) {
1091 handlers_[signum] = handler;
1092 }
1093
Yves Gerey665174f2018-06-19 15:03:05 +02001094 void ClearHandler(int signum) { handlers_.erase(signum); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001095
Yves Gerey665174f2018-06-19 15:03:05 +02001096 bool HasHandlers() { return !handlers_.empty(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001097
1098 private:
1099 typedef std::map<int, void (*)(int)> HandlerMap;
1100
1101 HandlerMap handlers_;
1102 // Our owner.
Yves Gerey665174f2018-06-19 15:03:05 +02001103 PhysicalSocketServer* owner_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001104};
1105
Yves Gerey665174f2018-06-19 15:03:05 +02001106#endif // WEBRTC_POSIX
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001107
1108#if defined(WEBRTC_WIN)
Peter Boström0c4e06b2015-10-07 12:23:21 +02001109static uint32_t FlagsToEvents(uint32_t events) {
1110 uint32_t ffFD = FD_CLOSE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001111 if (events & DE_READ)
1112 ffFD |= FD_READ;
1113 if (events & DE_WRITE)
1114 ffFD |= FD_WRITE;
1115 if (events & DE_CONNECT)
1116 ffFD |= FD_CONNECT;
1117 if (events & DE_ACCEPT)
1118 ffFD |= FD_ACCEPT;
1119 return ffFD;
1120}
1121
1122class EventDispatcher : public Dispatcher {
1123 public:
Yves Gerey665174f2018-06-19 15:03:05 +02001124 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001125 hev_ = WSACreateEvent();
1126 if (hev_) {
1127 ss_->Add(this);
1128 }
1129 }
1130
Steve Anton9de3aac2017-10-24 10:08:26 -07001131 ~EventDispatcher() override {
deadbeef37f5ecf2017-02-27 14:06:41 -08001132 if (hev_ != nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001133 ss_->Remove(this);
1134 WSACloseEvent(hev_);
deadbeef37f5ecf2017-02-27 14:06:41 -08001135 hev_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001136 }
1137 }
1138
1139 virtual void Signal() {
deadbeef37f5ecf2017-02-27 14:06:41 -08001140 if (hev_ != nullptr)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001141 WSASetEvent(hev_);
1142 }
1143
Steve Anton9de3aac2017-10-24 10:08:26 -07001144 uint32_t GetRequestedEvents() override { return 0; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001145
Steve Anton9de3aac2017-10-24 10:08:26 -07001146 void OnPreEvent(uint32_t ff) override { WSAResetEvent(hev_); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001147
Steve Anton9de3aac2017-10-24 10:08:26 -07001148 void OnEvent(uint32_t ff, int err) override {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001149
Steve Anton9de3aac2017-10-24 10:08:26 -07001150 WSAEVENT GetWSAEvent() override { return hev_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001151
Steve Anton9de3aac2017-10-24 10:08:26 -07001152 SOCKET GetSocket() override { return INVALID_SOCKET; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001153
Steve Anton9de3aac2017-10-24 10:08:26 -07001154 bool CheckSignalClose() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001155
Steve Anton9de3aac2017-10-24 10:08:26 -07001156 private:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001157 PhysicalSocketServer* ss_;
1158 WSAEVENT hev_;
1159};
honghaizcec0a082016-01-15 14:49:09 -08001160#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001161
1162// Sets the value of a boolean value to false when signaled.
1163class Signaler : public EventDispatcher {
1164 public:
Yves Gerey665174f2018-06-19 15:03:05 +02001165 Signaler(PhysicalSocketServer* ss, bool* pf) : EventDispatcher(ss), pf_(pf) {}
1166 ~Signaler() override {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001167
Peter Boström0c4e06b2015-10-07 12:23:21 +02001168 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001169 if (pf_)
1170 *pf_ = false;
1171 }
1172
1173 private:
Yves Gerey665174f2018-06-19 15:03:05 +02001174 bool* pf_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001175};
1176
Yves Gerey665174f2018-06-19 15:03:05 +02001177PhysicalSocketServer::PhysicalSocketServer() : fWait_(false) {
jbauchde4db112017-05-31 13:09:18 -07001178#if defined(WEBRTC_USE_EPOLL)
1179 // Since Linux 2.6.8, the size argument is ignored, but must be greater than
1180 // zero. Before that the size served as hint to the kernel for the amount of
1181 // space to initially allocate in internal data structures.
1182 epoll_fd_ = epoll_create(FD_SETSIZE);
1183 if (epoll_fd_ == -1) {
1184 // Not an error, will fall back to "select" below.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001185 RTC_LOG_E(LS_WARNING, EN, errno) << "epoll_create";
jbauchde4db112017-05-31 13:09:18 -07001186 epoll_fd_ = INVALID_SOCKET;
1187 }
1188#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001189 signal_wakeup_ = new Signaler(this, &fWait_);
1190#if defined(WEBRTC_WIN)
1191 socket_ev_ = WSACreateEvent();
1192#endif
1193}
1194
1195PhysicalSocketServer::~PhysicalSocketServer() {
1196#if defined(WEBRTC_WIN)
1197 WSACloseEvent(socket_ev_);
1198#endif
1199#if defined(WEBRTC_POSIX)
1200 signal_dispatcher_.reset();
1201#endif
1202 delete signal_wakeup_;
jbauchde4db112017-05-31 13:09:18 -07001203#if defined(WEBRTC_USE_EPOLL)
1204 if (epoll_fd_ != INVALID_SOCKET) {
1205 close(epoll_fd_);
1206 }
1207#endif
nisseede5da42017-01-12 05:15:36 -08001208 RTC_DCHECK(dispatchers_.empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001209}
1210
1211void PhysicalSocketServer::WakeUp() {
1212 signal_wakeup_->Signal();
1213}
1214
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001215Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
1216 PhysicalSocket* socket = new PhysicalSocket(this);
1217 if (socket->Create(family, type)) {
1218 return socket;
1219 } else {
1220 delete socket;
jbauch095ae152015-12-18 01:39:55 -08001221 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001222 }
1223}
1224
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001225AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
1226 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1227 if (dispatcher->Create(family, type)) {
1228 return dispatcher;
1229 } else {
1230 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001231 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001232 }
1233}
1234
1235AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
1236 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1237 if (dispatcher->Initialize()) {
1238 return dispatcher;
1239 } else {
1240 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001241 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001242 }
1243}
1244
Yves Gerey665174f2018-06-19 15:03:05 +02001245void PhysicalSocketServer::Add(Dispatcher* pdispatcher) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001246 CritScope cs(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001247 if (processing_dispatchers_) {
1248 // A dispatcher is being added while a "Wait" call is processing the
1249 // list of socket events.
1250 // Defer adding to "dispatchers_" set until processing is done to avoid
1251 // invalidating the iterator in "Wait".
1252 pending_remove_dispatchers_.erase(pdispatcher);
1253 pending_add_dispatchers_.insert(pdispatcher);
1254 } else {
1255 dispatchers_.insert(pdispatcher);
1256 }
1257#if defined(WEBRTC_USE_EPOLL)
1258 if (epoll_fd_ != INVALID_SOCKET) {
1259 AddEpoll(pdispatcher);
1260 }
1261#endif // WEBRTC_USE_EPOLL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001262}
1263
Yves Gerey665174f2018-06-19 15:03:05 +02001264void PhysicalSocketServer::Remove(Dispatcher* pdispatcher) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001265 CritScope cs(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001266 if (processing_dispatchers_) {
1267 // A dispatcher is being removed while a "Wait" call is processing the
1268 // list of socket events.
1269 // Defer removal from "dispatchers_" set until processing is done to avoid
1270 // invalidating the iterator in "Wait".
1271 if (!pending_add_dispatchers_.erase(pdispatcher) &&
1272 dispatchers_.find(pdispatcher) == dispatchers_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001273 RTC_LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
1274 << "dispatcher, potentially from a duplicate call to "
1275 << "Add.";
jbauchde4db112017-05-31 13:09:18 -07001276 return;
1277 }
1278
1279 pending_remove_dispatchers_.insert(pdispatcher);
1280 } else if (!dispatchers_.erase(pdispatcher)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001281 RTC_LOG(LS_WARNING)
1282 << "PhysicalSocketServer asked to remove a unknown "
1283 << "dispatcher, potentially from a duplicate call to Add.";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001284 return;
1285 }
jbauchde4db112017-05-31 13:09:18 -07001286#if defined(WEBRTC_USE_EPOLL)
1287 if (epoll_fd_ != INVALID_SOCKET) {
1288 RemoveEpoll(pdispatcher);
1289 }
1290#endif // WEBRTC_USE_EPOLL
1291}
1292
1293void PhysicalSocketServer::Update(Dispatcher* pdispatcher) {
1294#if defined(WEBRTC_USE_EPOLL)
1295 if (epoll_fd_ == INVALID_SOCKET) {
1296 return;
1297 }
1298
1299 CritScope cs(&crit_);
1300 if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1301 return;
1302 }
1303
1304 UpdateEpoll(pdispatcher);
1305#endif
1306}
1307
1308void PhysicalSocketServer::AddRemovePendingDispatchers() {
1309 if (!pending_add_dispatchers_.empty()) {
1310 for (Dispatcher* pdispatcher : pending_add_dispatchers_) {
1311 dispatchers_.insert(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001312 }
jbauchde4db112017-05-31 13:09:18 -07001313 pending_add_dispatchers_.clear();
1314 }
1315
1316 if (!pending_remove_dispatchers_.empty()) {
1317 for (Dispatcher* pdispatcher : pending_remove_dispatchers_) {
1318 dispatchers_.erase(pdispatcher);
1319 }
1320 pending_remove_dispatchers_.clear();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001321 }
1322}
1323
1324#if defined(WEBRTC_POSIX)
jbauchde4db112017-05-31 13:09:18 -07001325
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001326bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
jbauchde4db112017-05-31 13:09:18 -07001327#if defined(WEBRTC_USE_EPOLL)
1328 // We don't keep a dedicated "epoll" descriptor containing only the non-IO
1329 // (i.e. signaling) dispatcher, so "poll" will be used instead of the default
1330 // "select" to support sockets larger than FD_SETSIZE.
1331 if (!process_io) {
1332 return WaitPoll(cmsWait, signal_wakeup_);
1333 } else if (epoll_fd_ != INVALID_SOCKET) {
1334 return WaitEpoll(cmsWait);
1335 }
1336#endif
1337 return WaitSelect(cmsWait, process_io);
1338}
1339
1340static void ProcessEvents(Dispatcher* dispatcher,
1341 bool readable,
1342 bool writable,
1343 bool check_error) {
1344 int errcode = 0;
1345 // TODO(pthatcher): Should we set errcode if getsockopt fails?
1346 if (check_error) {
1347 socklen_t len = sizeof(errcode);
1348 ::getsockopt(dispatcher->GetDescriptor(), SOL_SOCKET, SO_ERROR, &errcode,
1349 &len);
1350 }
1351
1352 uint32_t ff = 0;
1353
1354 // Check readable descriptors. If we're waiting on an accept, signal
1355 // that. Otherwise we're waiting for data, check to see if we're
1356 // readable or really closed.
1357 // TODO(pthatcher): Only peek at TCP descriptors.
1358 if (readable) {
1359 if (dispatcher->GetRequestedEvents() & DE_ACCEPT) {
1360 ff |= DE_ACCEPT;
1361 } else if (errcode || dispatcher->IsDescriptorClosed()) {
1362 ff |= DE_CLOSE;
1363 } else {
1364 ff |= DE_READ;
1365 }
1366 }
1367
1368 // Check writable descriptors. If we're waiting on a connect, detect
1369 // success versus failure by the reaped error code.
1370 if (writable) {
1371 if (dispatcher->GetRequestedEvents() & DE_CONNECT) {
1372 if (!errcode) {
1373 ff |= DE_CONNECT;
1374 } else {
1375 ff |= DE_CLOSE;
1376 }
1377 } else {
1378 ff |= DE_WRITE;
1379 }
1380 }
1381
1382 // Tell the descriptor about the event.
1383 if (ff != 0) {
1384 dispatcher->OnPreEvent(ff);
1385 dispatcher->OnEvent(ff, errcode);
1386 }
1387}
1388
1389bool PhysicalSocketServer::WaitSelect(int cmsWait, bool process_io) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001390 // Calculate timing information
1391
deadbeef37f5ecf2017-02-27 14:06:41 -08001392 struct timeval* ptvWait = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001393 struct timeval tvWait;
1394 struct timeval tvStop;
1395 if (cmsWait != kForever) {
1396 // Calculate wait timeval
1397 tvWait.tv_sec = cmsWait / 1000;
1398 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1399 ptvWait = &tvWait;
1400
1401 // Calculate when to return in a timeval
deadbeef37f5ecf2017-02-27 14:06:41 -08001402 gettimeofday(&tvStop, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001403 tvStop.tv_sec += tvWait.tv_sec;
1404 tvStop.tv_usec += tvWait.tv_usec;
1405 if (tvStop.tv_usec >= 1000000) {
1406 tvStop.tv_usec -= 1000000;
1407 tvStop.tv_sec += 1;
1408 }
1409 }
1410
1411 // Zero all fd_sets. Don't need to do this inside the loop since
1412 // select() zeros the descriptors not signaled
1413
1414 fd_set fdsRead;
1415 FD_ZERO(&fdsRead);
1416 fd_set fdsWrite;
1417 FD_ZERO(&fdsWrite);
Yves Gerey665174f2018-06-19 15:03:05 +02001418// Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1419// inline assembly in FD_ZERO.
1420// http://crbug.com/344505
pbos@webrtc.org27e58982014-10-07 17:56:53 +00001421#ifdef MEMORY_SANITIZER
1422 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1423 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1424#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001425
1426 fWait_ = true;
1427
1428 while (fWait_) {
1429 int fdmax = -1;
1430 {
1431 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001432 // TODO(jbauch): Support re-entrant waiting.
1433 RTC_DCHECK(!processing_dispatchers_);
1434 for (Dispatcher* pdispatcher : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001435 // Query dispatchers for read and write wait state
nisseede5da42017-01-12 05:15:36 -08001436 RTC_DCHECK(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001437 if (!process_io && (pdispatcher != signal_wakeup_))
1438 continue;
1439 int fd = pdispatcher->GetDescriptor();
jbauchde4db112017-05-31 13:09:18 -07001440 // "select"ing a file descriptor that is equal to or larger than
1441 // FD_SETSIZE will result in undefined behavior.
1442 RTC_DCHECK_LT(fd, FD_SETSIZE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001443 if (fd > fdmax)
1444 fdmax = fd;
1445
Peter Boström0c4e06b2015-10-07 12:23:21 +02001446 uint32_t ff = pdispatcher->GetRequestedEvents();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001447 if (ff & (DE_READ | DE_ACCEPT))
1448 FD_SET(fd, &fdsRead);
1449 if (ff & (DE_WRITE | DE_CONNECT))
1450 FD_SET(fd, &fdsWrite);
1451 }
1452 }
1453
1454 // Wait then call handlers as appropriate
1455 // < 0 means error
1456 // 0 means timeout
1457 // > 0 means count of descriptors ready
deadbeef37f5ecf2017-02-27 14:06:41 -08001458 int n = select(fdmax + 1, &fdsRead, &fdsWrite, nullptr, ptvWait);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001459
1460 // If error, return error.
1461 if (n < 0) {
1462 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001463 RTC_LOG_E(LS_ERROR, EN, errno) << "select";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001464 return false;
1465 }
1466 // Else ignore the error and keep going. If this EINTR was for one of the
1467 // signals managed by this PhysicalSocketServer, the
1468 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1469 // iteration.
1470 } else if (n == 0) {
1471 // If timeout, return success
1472 return true;
1473 } else {
1474 // We have signaled descriptors
1475 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001476 processing_dispatchers_ = true;
1477 for (Dispatcher* pdispatcher : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001478 int fd = pdispatcher->GetDescriptor();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001479
jbauchde4db112017-05-31 13:09:18 -07001480 bool readable = FD_ISSET(fd, &fdsRead);
1481 if (readable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001482 FD_CLR(fd, &fdsRead);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001483 }
1484
jbauchde4db112017-05-31 13:09:18 -07001485 bool writable = FD_ISSET(fd, &fdsWrite);
1486 if (writable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001487 FD_CLR(fd, &fdsWrite);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001488 }
1489
jbauchde4db112017-05-31 13:09:18 -07001490 // The error code can be signaled through reads or writes.
1491 ProcessEvents(pdispatcher, readable, writable, readable || writable);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001492 }
jbauchde4db112017-05-31 13:09:18 -07001493
1494 processing_dispatchers_ = false;
1495 // Process deferred dispatchers that have been added/removed while the
1496 // events were handled above.
1497 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001498 }
1499
1500 // Recalc the time remaining to wait. Doing it here means it doesn't get
1501 // calced twice the first time through the loop
1502 if (ptvWait) {
1503 ptvWait->tv_sec = 0;
1504 ptvWait->tv_usec = 0;
1505 struct timeval tvT;
deadbeef37f5ecf2017-02-27 14:06:41 -08001506 gettimeofday(&tvT, nullptr);
Yves Gerey665174f2018-06-19 15:03:05 +02001507 if ((tvStop.tv_sec > tvT.tv_sec) ||
1508 ((tvStop.tv_sec == tvT.tv_sec) && (tvStop.tv_usec > tvT.tv_usec))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001509 ptvWait->tv_sec = tvStop.tv_sec - tvT.tv_sec;
1510 ptvWait->tv_usec = tvStop.tv_usec - tvT.tv_usec;
1511 if (ptvWait->tv_usec < 0) {
nisseede5da42017-01-12 05:15:36 -08001512 RTC_DCHECK(ptvWait->tv_sec > 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001513 ptvWait->tv_usec += 1000000;
1514 ptvWait->tv_sec -= 1;
1515 }
1516 }
1517 }
1518 }
1519
1520 return true;
1521}
1522
jbauchde4db112017-05-31 13:09:18 -07001523#if defined(WEBRTC_USE_EPOLL)
1524
1525// Initial number of events to process with one call to "epoll_wait".
1526static const size_t kInitialEpollEvents = 128;
1527
1528// Maximum number of events to process with one call to "epoll_wait".
1529static const size_t kMaxEpollEvents = 8192;
1530
1531void PhysicalSocketServer::AddEpoll(Dispatcher* pdispatcher) {
1532 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1533 int fd = pdispatcher->GetDescriptor();
1534 RTC_DCHECK(fd != INVALID_SOCKET);
1535 if (fd == INVALID_SOCKET) {
1536 return;
1537 }
1538
1539 struct epoll_event event = {0};
1540 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
1541 event.data.ptr = pdispatcher;
1542 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &event);
1543 RTC_DCHECK_EQ(err, 0);
1544 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001545 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_ADD";
jbauchde4db112017-05-31 13:09:18 -07001546 }
1547}
1548
1549void PhysicalSocketServer::RemoveEpoll(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 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &event);
1559 RTC_DCHECK(err == 0 || errno == ENOENT);
1560 if (err == -1) {
1561 if (errno == ENOENT) {
1562 // Socket has already been closed.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001563 RTC_LOG_E(LS_VERBOSE, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001564 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001565 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001566 }
1567 }
1568}
1569
1570void PhysicalSocketServer::UpdateEpoll(Dispatcher* pdispatcher) {
1571 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1572 int fd = pdispatcher->GetDescriptor();
1573 RTC_DCHECK(fd != INVALID_SOCKET);
1574 if (fd == INVALID_SOCKET) {
1575 return;
1576 }
1577
1578 struct epoll_event event = {0};
1579 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
1580 event.data.ptr = pdispatcher;
1581 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &event);
1582 RTC_DCHECK_EQ(err, 0);
1583 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001584 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_MOD";
jbauchde4db112017-05-31 13:09:18 -07001585 }
1586}
1587
1588bool PhysicalSocketServer::WaitEpoll(int cmsWait) {
1589 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1590 int64_t tvWait = -1;
1591 int64_t tvStop = -1;
1592 if (cmsWait != kForever) {
1593 tvWait = cmsWait;
1594 tvStop = TimeAfter(cmsWait);
1595 }
1596
1597 if (epoll_events_.empty()) {
1598 // The initial space to receive events is created only if epoll is used.
1599 epoll_events_.resize(kInitialEpollEvents);
1600 }
1601
1602 fWait_ = true;
1603
1604 while (fWait_) {
1605 // Wait then call handlers as appropriate
1606 // < 0 means error
1607 // 0 means timeout
1608 // > 0 means count of descriptors ready
1609 int n = epoll_wait(epoll_fd_, &epoll_events_[0],
1610 static_cast<int>(epoll_events_.size()),
1611 static_cast<int>(tvWait));
1612 if (n < 0) {
1613 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001614 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll";
jbauchde4db112017-05-31 13:09:18 -07001615 return false;
1616 }
1617 // Else ignore the error and keep going. If this EINTR was for one of the
1618 // signals managed by this PhysicalSocketServer, the
1619 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1620 // iteration.
1621 } else if (n == 0) {
1622 // If timeout, return success
1623 return true;
1624 } else {
1625 // We have signaled descriptors
1626 CritScope cr(&crit_);
1627 for (int i = 0; i < n; ++i) {
1628 const epoll_event& event = epoll_events_[i];
1629 Dispatcher* pdispatcher = static_cast<Dispatcher*>(event.data.ptr);
1630 if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1631 // The dispatcher for this socket no longer exists.
1632 continue;
1633 }
1634
1635 bool readable = (event.events & (EPOLLIN | EPOLLPRI));
1636 bool writable = (event.events & EPOLLOUT);
1637 bool check_error = (event.events & (EPOLLRDHUP | EPOLLERR | EPOLLHUP));
1638
1639 ProcessEvents(pdispatcher, readable, writable, check_error);
1640 }
1641 }
1642
1643 if (static_cast<size_t>(n) == epoll_events_.size() &&
1644 epoll_events_.size() < kMaxEpollEvents) {
1645 // We used the complete space to receive events, increase size for future
1646 // iterations.
1647 epoll_events_.resize(std::max(epoll_events_.size() * 2, kMaxEpollEvents));
1648 }
1649
1650 if (cmsWait != kForever) {
1651 tvWait = TimeDiff(tvStop, TimeMillis());
1652 if (tvWait < 0) {
1653 // Return success on timeout.
1654 return true;
1655 }
1656 }
1657 }
1658
1659 return true;
1660}
1661
1662bool PhysicalSocketServer::WaitPoll(int cmsWait, Dispatcher* dispatcher) {
1663 RTC_DCHECK(dispatcher);
1664 int64_t tvWait = -1;
1665 int64_t tvStop = -1;
1666 if (cmsWait != kForever) {
1667 tvWait = cmsWait;
1668 tvStop = TimeAfter(cmsWait);
1669 }
1670
1671 fWait_ = true;
1672
1673 struct pollfd fds = {0};
1674 int fd = dispatcher->GetDescriptor();
1675 fds.fd = fd;
1676
1677 while (fWait_) {
1678 uint32_t ff = dispatcher->GetRequestedEvents();
1679 fds.events = 0;
1680 if (ff & (DE_READ | DE_ACCEPT)) {
1681 fds.events |= POLLIN;
1682 }
1683 if (ff & (DE_WRITE | DE_CONNECT)) {
1684 fds.events |= POLLOUT;
1685 }
1686 fds.revents = 0;
1687
1688 // Wait then call handlers as appropriate
1689 // < 0 means error
1690 // 0 means timeout
1691 // > 0 means count of descriptors ready
1692 int n = poll(&fds, 1, static_cast<int>(tvWait));
1693 if (n < 0) {
1694 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001695 RTC_LOG_E(LS_ERROR, EN, errno) << "poll";
jbauchde4db112017-05-31 13:09:18 -07001696 return false;
1697 }
1698 // Else ignore the error and keep going. If this EINTR was for one of the
1699 // signals managed by this PhysicalSocketServer, the
1700 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1701 // iteration.
1702 } else if (n == 0) {
1703 // If timeout, return success
1704 return true;
1705 } else {
1706 // We have signaled descriptors (should only be the passed dispatcher).
1707 RTC_DCHECK_EQ(n, 1);
1708 RTC_DCHECK_EQ(fds.fd, fd);
1709
1710 bool readable = (fds.revents & (POLLIN | POLLPRI));
1711 bool writable = (fds.revents & POLLOUT);
1712 bool check_error = (fds.revents & (POLLRDHUP | POLLERR | POLLHUP));
1713
1714 ProcessEvents(dispatcher, readable, writable, check_error);
1715 }
1716
1717 if (cmsWait != kForever) {
1718 tvWait = TimeDiff(tvStop, TimeMillis());
1719 if (tvWait < 0) {
1720 // Return success on timeout.
1721 return true;
1722 }
1723 }
1724 }
1725
1726 return true;
1727}
1728
1729#endif // WEBRTC_USE_EPOLL
1730
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001731static void GlobalSignalHandler(int signum) {
1732 PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
1733}
1734
1735bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
1736 void (*handler)(int)) {
1737 // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
1738 // otherwise set one.
1739 if (handler == SIG_IGN || handler == SIG_DFL) {
1740 if (!InstallSignal(signum, handler)) {
1741 return false;
1742 }
1743 if (signal_dispatcher_) {
1744 signal_dispatcher_->ClearHandler(signum);
1745 if (!signal_dispatcher_->HasHandlers()) {
1746 signal_dispatcher_.reset();
1747 }
1748 }
1749 } else {
1750 if (!signal_dispatcher_) {
1751 signal_dispatcher_.reset(new PosixSignalDispatcher(this));
1752 }
1753 signal_dispatcher_->SetHandler(signum, handler);
1754 if (!InstallSignal(signum, &GlobalSignalHandler)) {
1755 return false;
1756 }
1757 }
1758 return true;
1759}
1760
1761Dispatcher* PhysicalSocketServer::signal_dispatcher() {
1762 return signal_dispatcher_.get();
1763}
1764
1765bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
1766 struct sigaction act;
1767 // It doesn't really matter what we set this mask to.
1768 if (sigemptyset(&act.sa_mask) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001769 RTC_LOG_ERR(LS_ERROR) << "Couldn't set mask";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001770 return false;
1771 }
1772 act.sa_handler = handler;
1773#if !defined(__native_client__)
1774 // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
1775 // and it's a nuisance. Though some syscalls still return EINTR and there's no
1776 // real standard for which ones. :(
1777 act.sa_flags = SA_RESTART;
1778#else
1779 act.sa_flags = 0;
1780#endif
deadbeef37f5ecf2017-02-27 14:06:41 -08001781 if (sigaction(signum, &act, nullptr) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001782 RTC_LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001783 return false;
1784 }
1785 return true;
1786}
1787#endif // WEBRTC_POSIX
1788
1789#if defined(WEBRTC_WIN)
1790bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
Honghai Zhang82d78622016-05-06 11:29:15 -07001791 int64_t cmsTotal = cmsWait;
1792 int64_t cmsElapsed = 0;
1793 int64_t msStart = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001794
1795 fWait_ = true;
1796 while (fWait_) {
1797 std::vector<WSAEVENT> events;
Yves Gerey665174f2018-06-19 15:03:05 +02001798 std::vector<Dispatcher*> event_owners;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001799
1800 events.push_back(socket_ev_);
1801
1802 {
1803 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001804 // TODO(jbauch): Support re-entrant waiting.
1805 RTC_DCHECK(!processing_dispatchers_);
1806
1807 // Calling "CheckSignalClose" might remove a closed dispatcher from the
1808 // set. This must be deferred to prevent invalidating the iterator.
1809 processing_dispatchers_ = true;
1810 for (Dispatcher* disp : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001811 if (!process_io && (disp != signal_wakeup_))
1812 continue;
1813 SOCKET s = disp->GetSocket();
1814 if (disp->CheckSignalClose()) {
1815 // We just signalled close, don't poll this socket
1816 } else if (s != INVALID_SOCKET) {
Yves Gerey665174f2018-06-19 15:03:05 +02001817 WSAEventSelect(s, events[0],
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001818 FlagsToEvents(disp->GetRequestedEvents()));
1819 } else {
1820 events.push_back(disp->GetWSAEvent());
1821 event_owners.push_back(disp);
1822 }
1823 }
jbauchde4db112017-05-31 13:09:18 -07001824
1825 processing_dispatchers_ = false;
1826 // Process deferred dispatchers that have been added/removed while the
1827 // events were handled above.
1828 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001829 }
1830
1831 // Which is shorter, the delay wait or the asked wait?
1832
Honghai Zhang82d78622016-05-06 11:29:15 -07001833 int64_t cmsNext;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001834 if (cmsWait == kForever) {
1835 cmsNext = cmsWait;
1836 } else {
Honghai Zhang82d78622016-05-06 11:29:15 -07001837 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001838 }
1839
1840 // Wait for one of the events to signal
Yves Gerey665174f2018-06-19 15:03:05 +02001841 DWORD dw =
1842 WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()), &events[0],
1843 false, static_cast<DWORD>(cmsNext), false);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001844
1845 if (dw == WSA_WAIT_FAILED) {
1846 // Failed?
jbauch095ae152015-12-18 01:39:55 -08001847 // TODO(pthatcher): need a better strategy than this!
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001848 WSAGetLastError();
nissec80e7412017-01-11 05:56:46 -08001849 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001850 return false;
1851 } else if (dw == WSA_WAIT_TIMEOUT) {
1852 // Timeout?
1853 return true;
1854 } else {
1855 // Figure out which one it is and call it
1856 CritScope cr(&crit_);
1857 int index = dw - WSA_WAIT_EVENT_0;
1858 if (index > 0) {
Yves Gerey665174f2018-06-19 15:03:05 +02001859 --index; // The first event is the socket event
jbauchde4db112017-05-31 13:09:18 -07001860 Dispatcher* disp = event_owners[index];
1861 // The dispatcher could have been removed while waiting for events.
1862 if (dispatchers_.find(disp) != dispatchers_.end()) {
1863 disp->OnPreEvent(0);
1864 disp->OnEvent(0, 0);
1865 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001866 } else if (process_io) {
jbauchde4db112017-05-31 13:09:18 -07001867 processing_dispatchers_ = true;
1868 for (Dispatcher* disp : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001869 SOCKET s = disp->GetSocket();
1870 if (s == INVALID_SOCKET)
1871 continue;
1872
1873 WSANETWORKEVENTS wsaEvents;
1874 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1875 if (err == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001876 {
1877 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1878 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001879 RTC_LOG(WARNING)
1880 << "PhysicalSocketServer got FD_READ_BIT error "
1881 << wsaEvents.iErrorCode[FD_READ_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001882 }
1883 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1884 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001885 RTC_LOG(WARNING)
1886 << "PhysicalSocketServer got FD_WRITE_BIT error "
1887 << wsaEvents.iErrorCode[FD_WRITE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001888 }
1889 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1890 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001891 RTC_LOG(WARNING)
1892 << "PhysicalSocketServer got FD_CONNECT_BIT error "
1893 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001894 }
1895 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1896 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001897 RTC_LOG(WARNING)
1898 << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1899 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001900 }
1901 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1902 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001903 RTC_LOG(WARNING)
1904 << "PhysicalSocketServer got FD_CLOSE_BIT error "
1905 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001906 }
1907 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001908 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001909 int errcode = 0;
1910 if (wsaEvents.lNetworkEvents & FD_READ)
1911 ff |= DE_READ;
1912 if (wsaEvents.lNetworkEvents & FD_WRITE)
1913 ff |= DE_WRITE;
1914 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1915 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1916 ff |= DE_CONNECT;
1917 } else {
1918 ff |= DE_CLOSE;
1919 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1920 }
1921 }
1922 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1923 ff |= DE_ACCEPT;
1924 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1925 ff |= DE_CLOSE;
1926 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1927 }
1928 if (ff != 0) {
1929 disp->OnPreEvent(ff);
1930 disp->OnEvent(ff, errcode);
1931 }
1932 }
1933 }
jbauchde4db112017-05-31 13:09:18 -07001934
1935 processing_dispatchers_ = false;
1936 // Process deferred dispatchers that have been added/removed while the
1937 // events were handled above.
1938 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001939 }
1940
1941 // Reset the network event until new activity occurs
1942 WSAResetEvent(socket_ev_);
1943 }
1944
1945 // Break?
1946 if (!fWait_)
1947 break;
1948 cmsElapsed = TimeSince(msStart);
1949 if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
Yves Gerey665174f2018-06-19 15:03:05 +02001950 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001951 }
1952 }
1953
1954 // Done
1955 return true;
1956}
honghaizcec0a082016-01-15 14:49:09 -08001957#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001958
1959} // namespace rtc