blob: 0d5fc525242d3993f3a7850a035c432e103c9976 [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
13#pragma warning(disable:4786)
14#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)
21#include <string.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000022#include <fcntl.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
Stefan Holmer9131efd2016-05-23 18:19:26 +020027#include <sys/ioctl.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000028#include <sys/time.h>
29#include <sys/select.h>
30#include <unistd.h>
31#include <signal.h>
32#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"
48#include "rtc_base/basictypes.h"
49#include "rtc_base/byteorder.h"
50#include "rtc_base/checks.h"
51#include "rtc_base/logging.h"
52#include "rtc_base/networkmonitor.h"
53#include "rtc_base/nullsocketserver.h"
54#include "rtc_base/timeutils.h"
55#include "rtc_base/win32socketinit.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000056
Patrik Höglunda8005cf2017-12-13 16:05:42 +010057#if defined(WEBRTC_WIN)
58#define LAST_SYSTEM_ERROR (::GetLastError())
59#elif defined(__native_client__) && __native_client__
60#define LAST_SYSTEM_ERROR (0)
61#elif defined(WEBRTC_POSIX)
62#define LAST_SYSTEM_ERROR (errno)
63#endif // WEBRTC_WIN
64
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000065#if defined(WEBRTC_POSIX)
66#include <netinet/tcp.h> // for TCP_NODELAY
67#define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h
68typedef void* SockOptArg;
Stefan Holmer9131efd2016-05-23 18:19:26 +020069
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000070#endif // WEBRTC_POSIX
71
Stefan Holmer3ebb3ef2016-05-23 20:26:11 +020072#if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) && !defined(__native_client__)
73
Stefan Holmer9131efd2016-05-23 18:19:26 +020074int64_t GetSocketRecvTimestamp(int socket) {
75 struct timeval tv_ioctl;
76 int ret = ioctl(socket, SIOCGSTAMP, &tv_ioctl);
77 if (ret != 0)
78 return -1;
79 int64_t timestamp =
80 rtc::kNumMicrosecsPerSec * static_cast<int64_t>(tv_ioctl.tv_sec) +
81 static_cast<int64_t>(tv_ioctl.tv_usec);
82 return timestamp;
83}
84
85#else
86
87int64_t GetSocketRecvTimestamp(int socket) {
88 return -1;
89}
90#endif
91
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000092#if defined(WEBRTC_WIN)
93typedef char* SockOptArg;
94#endif
95
jbauchde4db112017-05-31 13:09:18 -070096#if defined(WEBRTC_USE_EPOLL)
97// POLLRDHUP / EPOLLRDHUP are only defined starting with Linux 2.6.17.
98#if !defined(POLLRDHUP)
99#define POLLRDHUP 0x2000
100#endif
101#if !defined(EPOLLRDHUP)
102#define EPOLLRDHUP 0x2000
103#endif
104#endif
105
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000106namespace rtc {
107
danilchapbebf54c2016-04-28 01:32:48 -0700108std::unique_ptr<SocketServer> SocketServer::CreateDefault() {
109#if defined(__native_client__)
110 return std::unique_ptr<SocketServer>(new rtc::NullSocketServer);
111#else
112 return std::unique_ptr<SocketServer>(new rtc::PhysicalSocketServer);
113#endif
114}
115
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000116#if defined(WEBRTC_WIN)
117// Standard MTUs, from RFC 1191
Peter Boström0c4e06b2015-10-07 12:23:21 +0200118const uint16_t PACKET_MAXIMUMS[] = {
119 65535, // Theoretical maximum, Hyperchannel
120 32000, // Nothing
121 17914, // 16Mb IBM Token Ring
122 8166, // IEEE 802.4
123 // 4464, // IEEE 802.5 (4Mb max)
124 4352, // FDDI
125 // 2048, // Wideband Network
126 2002, // IEEE 802.5 (4Mb recommended)
127 // 1536, // Expermental Ethernet Networks
128 // 1500, // Ethernet, Point-to-Point (default)
129 1492, // IEEE 802.3
130 1006, // SLIP, ARPANET
131 // 576, // X.25 Networks
132 // 544, // DEC IP Portal
133 // 512, // NETBIOS
134 508, // IEEE 802/Source-Rt Bridge, ARCNET
135 296, // Point-to-Point (low delay)
136 68, // Official minimum
137 0, // End of list marker
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000138};
139
140static const int IP_HEADER_SIZE = 20u;
141static const int IPV6_HEADER_SIZE = 40u;
142static const int ICMP_HEADER_SIZE = 8u;
143static const int ICMP_PING_TIMEOUT_MILLIS = 10000u;
144#endif
145
jbauch095ae152015-12-18 01:39:55 -0800146PhysicalSocket::PhysicalSocket(PhysicalSocketServer* ss, SOCKET s)
jbauch577f5dc2017-05-17 16:32:26 -0700147 : ss_(ss), s_(s), error_(0),
jbauch095ae152015-12-18 01:39:55 -0800148 state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED),
149 resolver_(nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000150#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800151 // EnsureWinsockInit() ensures that winsock is initialized. The default
152 // version of this function doesn't do anything because winsock is
153 // initialized by constructor of a static object. If neccessary libjingle
154 // users can link it with a different version of this function by replacing
155 // win32socketinit.cc. See win32socketinit.cc for more details.
156 EnsureWinsockInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000157#endif
jbauch095ae152015-12-18 01:39:55 -0800158 if (s_ != INVALID_SOCKET) {
jbauch577f5dc2017-05-17 16:32:26 -0700159 SetEnabledEvents(DE_READ | DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000160
jbauch095ae152015-12-18 01:39:55 -0800161 int type = SOCK_STREAM;
162 socklen_t len = sizeof(type);
nissec16fa5e2017-02-07 07:18:43 -0800163 const int res =
164 getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len);
165 RTC_DCHECK_EQ(0, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000166 udp_ = (SOCK_DGRAM == type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000167 }
jbauch095ae152015-12-18 01:39:55 -0800168}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000169
jbauch095ae152015-12-18 01:39:55 -0800170PhysicalSocket::~PhysicalSocket() {
171 Close();
172}
173
174bool PhysicalSocket::Create(int family, int type) {
175 Close();
176 s_ = ::socket(family, type, 0);
177 udp_ = (SOCK_DGRAM == type);
178 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700179 if (udp_) {
180 SetEnabledEvents(DE_READ | DE_WRITE);
181 }
jbauch095ae152015-12-18 01:39:55 -0800182 return s_ != INVALID_SOCKET;
183}
184
185SocketAddress PhysicalSocket::GetLocalAddress() const {
186 sockaddr_storage addr_storage = {0};
187 socklen_t addrlen = sizeof(addr_storage);
188 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
189 int result = ::getsockname(s_, addr, &addrlen);
190 SocketAddress address;
191 if (result >= 0) {
192 SocketAddressFromSockAddrStorage(addr_storage, &address);
193 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100194 RTC_LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
195 << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000196 }
jbauch095ae152015-12-18 01:39:55 -0800197 return address;
198}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000199
jbauch095ae152015-12-18 01:39:55 -0800200SocketAddress PhysicalSocket::GetRemoteAddress() const {
201 sockaddr_storage addr_storage = {0};
202 socklen_t addrlen = sizeof(addr_storage);
203 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
204 int result = ::getpeername(s_, addr, &addrlen);
205 SocketAddress address;
206 if (result >= 0) {
207 SocketAddressFromSockAddrStorage(addr_storage, &address);
208 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100209 RTC_LOG(LS_WARNING)
210 << "GetRemoteAddress: unable to get remote addr, socket=" << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000211 }
jbauch095ae152015-12-18 01:39:55 -0800212 return address;
213}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000214
jbauch095ae152015-12-18 01:39:55 -0800215int PhysicalSocket::Bind(const SocketAddress& bind_addr) {
deadbeefc874d122017-02-13 15:41:59 -0800216 SocketAddress copied_bind_addr = bind_addr;
217 // If a network binder is available, use it to bind a socket to an interface
218 // instead of bind(), since this is more reliable on an OS with a weak host
219 // model.
deadbeef9ffa13f2017-02-21 16:18:00 -0800220 if (ss_->network_binder() && !bind_addr.IsAnyIP()) {
deadbeefc874d122017-02-13 15:41:59 -0800221 NetworkBindingResult result =
222 ss_->network_binder()->BindSocketToNetwork(s_, bind_addr.ipaddr());
223 if (result == NetworkBindingResult::SUCCESS) {
224 // Since the network binder handled binding the socket to the desired
225 // network interface, we don't need to (and shouldn't) include an IP in
226 // the bind() call; bind() just needs to assign a port.
227 copied_bind_addr.SetIP(GetAnyIP(copied_bind_addr.ipaddr().family()));
228 } else if (result == NetworkBindingResult::NOT_IMPLEMENTED) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100229 RTC_LOG(LS_INFO) << "Can't bind socket to network because "
230 "network binding is not implemented for this OS.";
deadbeefc874d122017-02-13 15:41:59 -0800231 } else {
232 if (bind_addr.IsLoopbackIP()) {
233 // If we couldn't bind to a loopback IP (which should only happen in
234 // test scenarios), continue on. This may be expected behavior.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100235 RTC_LOG(LS_VERBOSE) << "Binding socket to loopback address "
236 << bind_addr.ipaddr().ToString()
237 << " failed; result: " << static_cast<int>(result);
deadbeefc874d122017-02-13 15:41:59 -0800238 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100239 RTC_LOG(LS_WARNING) << "Binding socket to network address "
240 << bind_addr.ipaddr().ToString()
241 << " failed; result: " << static_cast<int>(result);
deadbeefc874d122017-02-13 15:41:59 -0800242 // If a network binding was attempted and failed, we should stop here
243 // and not try to use the socket. Otherwise, we may end up sending
244 // packets with an invalid source address.
245 // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=7026
246 return -1;
247 }
248 }
249 }
jbauch095ae152015-12-18 01:39:55 -0800250 sockaddr_storage addr_storage;
deadbeefc874d122017-02-13 15:41:59 -0800251 size_t len = copied_bind_addr.ToSockAddrStorage(&addr_storage);
jbauch095ae152015-12-18 01:39:55 -0800252 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
253 int err = ::bind(s_, addr, static_cast<int>(len));
254 UpdateLastError();
tfarinaa41ab932015-10-30 16:08:48 -0700255#if !defined(NDEBUG)
jbauch095ae152015-12-18 01:39:55 -0800256 if (0 == err) {
257 dbg_addr_ = "Bound @ ";
258 dbg_addr_.append(GetLocalAddress().ToString());
259 }
tfarinaa41ab932015-10-30 16:08:48 -0700260#endif
jbauch095ae152015-12-18 01:39:55 -0800261 return err;
262}
263
264int PhysicalSocket::Connect(const SocketAddress& addr) {
265 // TODO(pthatcher): Implicit creation is required to reconnect...
266 // ...but should we make it more explicit?
267 if (state_ != CS_CLOSED) {
268 SetError(EALREADY);
269 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000270 }
jbauch095ae152015-12-18 01:39:55 -0800271 if (addr.IsUnresolvedIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100272 RTC_LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
jbauch095ae152015-12-18 01:39:55 -0800273 resolver_ = new AsyncResolver();
274 resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult);
275 resolver_->Start(addr);
276 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000277 return 0;
278 }
279
jbauch095ae152015-12-18 01:39:55 -0800280 return DoConnect(addr);
281}
282
283int PhysicalSocket::DoConnect(const SocketAddress& connect_addr) {
284 if ((s_ == INVALID_SOCKET) &&
285 !Create(connect_addr.family(), SOCK_STREAM)) {
286 return SOCKET_ERROR;
287 }
288 sockaddr_storage addr_storage;
289 size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
290 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
291 int err = ::connect(s_, addr, static_cast<int>(len));
292 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700293 uint8_t events = DE_READ | DE_WRITE;
jbauch095ae152015-12-18 01:39:55 -0800294 if (err == 0) {
295 state_ = CS_CONNECTED;
296 } else if (IsBlockingError(GetError())) {
297 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700298 events |= DE_CONNECT;
jbauch095ae152015-12-18 01:39:55 -0800299 } else {
300 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000301 }
302
jbauch577f5dc2017-05-17 16:32:26 -0700303 EnableEvents(events);
jbauch095ae152015-12-18 01:39:55 -0800304 return 0;
305}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000306
jbauch095ae152015-12-18 01:39:55 -0800307int PhysicalSocket::GetError() const {
308 CritScope cs(&crit_);
309 return error_;
310}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000311
jbauch095ae152015-12-18 01:39:55 -0800312void PhysicalSocket::SetError(int error) {
313 CritScope cs(&crit_);
314 error_ = error;
315}
316
317AsyncSocket::ConnState PhysicalSocket::GetState() const {
318 return state_;
319}
320
321int PhysicalSocket::GetOption(Option opt, int* value) {
322 int slevel;
323 int sopt;
324 if (TranslateOption(opt, &slevel, &sopt) == -1)
325 return -1;
326 socklen_t optlen = sizeof(*value);
327 int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
328 if (ret != -1 && opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000329#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800330 *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000331#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000332 }
jbauch095ae152015-12-18 01:39:55 -0800333 return ret;
334}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000335
jbauch095ae152015-12-18 01:39:55 -0800336int PhysicalSocket::SetOption(Option opt, int value) {
337 int slevel;
338 int sopt;
339 if (TranslateOption(opt, &slevel, &sopt) == -1)
340 return -1;
341 if (opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000342#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800343 value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000344#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000345 }
jbauch095ae152015-12-18 01:39:55 -0800346 return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
347}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000348
jbauch095ae152015-12-18 01:39:55 -0800349int PhysicalSocket::Send(const void* pv, size_t cb) {
jbauchf2a2bf42016-02-03 16:45:32 -0800350 int sent = DoSend(s_, reinterpret_cast<const char *>(pv),
351 static_cast<int>(cb),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000352#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800353 // Suppress SIGPIPE. Without this, attempting to send on a socket whose
354 // other end is closed will result in a SIGPIPE signal being raised to
355 // our process, which by default will terminate the process, which we
356 // don't want. By specifying this flag, we'll just get the error EPIPE
357 // instead and can handle the error gracefully.
358 MSG_NOSIGNAL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000359#else
jbauch095ae152015-12-18 01:39:55 -0800360 0
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000361#endif
jbauch095ae152015-12-18 01:39:55 -0800362 );
363 UpdateLastError();
364 MaybeRemapSendError();
365 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800366 RTC_DCHECK(sent <= static_cast<int>(cb));
jbauchf2a2bf42016-02-03 16:45:32 -0800367 if ((sent > 0 && sent < static_cast<int>(cb)) ||
368 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700369 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000370 }
jbauch095ae152015-12-18 01:39:55 -0800371 return sent;
372}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000373
jbauch095ae152015-12-18 01:39:55 -0800374int PhysicalSocket::SendTo(const void* buffer,
375 size_t length,
376 const SocketAddress& addr) {
377 sockaddr_storage saddr;
378 size_t len = addr.ToSockAddrStorage(&saddr);
jbauchf2a2bf42016-02-03 16:45:32 -0800379 int sent = DoSendTo(
jbauch095ae152015-12-18 01:39:55 -0800380 s_, static_cast<const char *>(buffer), static_cast<int>(length),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000381#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800382 // Suppress SIGPIPE. See above for explanation.
383 MSG_NOSIGNAL,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000384#else
jbauch095ae152015-12-18 01:39:55 -0800385 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000386#endif
jbauch095ae152015-12-18 01:39:55 -0800387 reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
388 UpdateLastError();
389 MaybeRemapSendError();
390 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800391 RTC_DCHECK(sent <= static_cast<int>(length));
jbauchf2a2bf42016-02-03 16:45:32 -0800392 if ((sent > 0 && sent < static_cast<int>(length)) ||
393 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700394 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000395 }
jbauch095ae152015-12-18 01:39:55 -0800396 return sent;
397}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000398
Stefan Holmer9131efd2016-05-23 18:19:26 +0200399int PhysicalSocket::Recv(void* buffer, size_t length, int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800400 int received = ::recv(s_, static_cast<char*>(buffer),
401 static_cast<int>(length), 0);
402 if ((received == 0) && (length != 0)) {
403 // Note: on graceful shutdown, recv can return 0. In this case, we
404 // pretend it is blocking, and then signal close, so that simplifying
405 // assumptions can be made about Recv.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100406 RTC_LOG(LS_WARNING) << "EOF from socket; deferring close event";
jbauch095ae152015-12-18 01:39:55 -0800407 // Must turn this back on so that the select() loop will notice the close
408 // event.
jbauch577f5dc2017-05-17 16:32:26 -0700409 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800410 SetError(EWOULDBLOCK);
411 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000412 }
Stefan Holmer9131efd2016-05-23 18:19:26 +0200413 if (timestamp) {
414 *timestamp = GetSocketRecvTimestamp(s_);
415 }
jbauch095ae152015-12-18 01:39:55 -0800416 UpdateLastError();
417 int error = GetError();
418 bool success = (received >= 0) || IsBlockingError(error);
419 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700420 EnableEvents(DE_READ);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000421 }
jbauch095ae152015-12-18 01:39:55 -0800422 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100423 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000424 }
jbauch095ae152015-12-18 01:39:55 -0800425 return received;
426}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000427
jbauch095ae152015-12-18 01:39:55 -0800428int PhysicalSocket::RecvFrom(void* buffer,
429 size_t length,
Stefan Holmer9131efd2016-05-23 18:19:26 +0200430 SocketAddress* out_addr,
431 int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800432 sockaddr_storage addr_storage;
433 socklen_t addr_len = sizeof(addr_storage);
434 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
435 int received = ::recvfrom(s_, static_cast<char*>(buffer),
436 static_cast<int>(length), 0, addr, &addr_len);
Stefan Holmer9131efd2016-05-23 18:19:26 +0200437 if (timestamp) {
438 *timestamp = GetSocketRecvTimestamp(s_);
439 }
jbauch095ae152015-12-18 01:39:55 -0800440 UpdateLastError();
441 if ((received >= 0) && (out_addr != nullptr))
442 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
443 int error = GetError();
444 bool success = (received >= 0) || IsBlockingError(error);
445 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700446 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800447 }
448 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100449 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
jbauch095ae152015-12-18 01:39:55 -0800450 }
451 return received;
452}
453
454int PhysicalSocket::Listen(int backlog) {
455 int err = ::listen(s_, backlog);
456 UpdateLastError();
457 if (err == 0) {
458 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700459 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800460#if !defined(NDEBUG)
461 dbg_addr_ = "Listening @ ";
462 dbg_addr_.append(GetLocalAddress().ToString());
463#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000464 }
jbauch095ae152015-12-18 01:39:55 -0800465 return err;
466}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000467
jbauch095ae152015-12-18 01:39:55 -0800468AsyncSocket* PhysicalSocket::Accept(SocketAddress* out_addr) {
469 // Always re-subscribe DE_ACCEPT to make sure new incoming connections will
470 // trigger an event even if DoAccept returns an error here.
jbauch577f5dc2017-05-17 16:32:26 -0700471 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800472 sockaddr_storage addr_storage;
473 socklen_t addr_len = sizeof(addr_storage);
474 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
475 SOCKET s = DoAccept(s_, addr, &addr_len);
476 UpdateLastError();
477 if (s == INVALID_SOCKET)
478 return nullptr;
479 if (out_addr != nullptr)
480 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
481 return ss_->WrapSocket(s);
482}
483
484int PhysicalSocket::Close() {
485 if (s_ == INVALID_SOCKET)
486 return 0;
487 int err = ::closesocket(s_);
488 UpdateLastError();
489 s_ = INVALID_SOCKET;
490 state_ = CS_CLOSED;
jbauch577f5dc2017-05-17 16:32:26 -0700491 SetEnabledEvents(0);
jbauch095ae152015-12-18 01:39:55 -0800492 if (resolver_) {
493 resolver_->Destroy(false);
494 resolver_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000495 }
jbauch095ae152015-12-18 01:39:55 -0800496 return err;
497}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000498
jbauch095ae152015-12-18 01:39:55 -0800499SOCKET PhysicalSocket::DoAccept(SOCKET socket,
500 sockaddr* addr,
501 socklen_t* addrlen) {
502 return ::accept(socket, addr, addrlen);
503}
504
jbauchf2a2bf42016-02-03 16:45:32 -0800505int PhysicalSocket::DoSend(SOCKET socket, const char* buf, int len, int flags) {
506 return ::send(socket, buf, len, flags);
507}
508
509int PhysicalSocket::DoSendTo(SOCKET socket,
510 const char* buf,
511 int len,
512 int flags,
513 const struct sockaddr* dest_addr,
514 socklen_t addrlen) {
515 return ::sendto(socket, buf, len, flags, dest_addr, addrlen);
516}
517
jbauch095ae152015-12-18 01:39:55 -0800518void PhysicalSocket::OnResolveResult(AsyncResolverInterface* resolver) {
519 if (resolver != resolver_) {
520 return;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000521 }
522
jbauch095ae152015-12-18 01:39:55 -0800523 int error = resolver_->GetError();
524 if (error == 0) {
525 error = DoConnect(resolver_->address());
526 } else {
527 Close();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000528 }
529
jbauch095ae152015-12-18 01:39:55 -0800530 if (error) {
531 SetError(error);
532 SignalCloseEvent(this, error);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000533 }
jbauch095ae152015-12-18 01:39:55 -0800534}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000535
jbauch095ae152015-12-18 01:39:55 -0800536void PhysicalSocket::UpdateLastError() {
Patrik Höglunda8005cf2017-12-13 16:05:42 +0100537 SetError(LAST_SYSTEM_ERROR);
jbauch095ae152015-12-18 01:39:55 -0800538}
539
540void PhysicalSocket::MaybeRemapSendError() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000541#if defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800542 // https://developer.apple.com/library/mac/documentation/Darwin/
543 // Reference/ManPages/man2/sendto.2.html
544 // ENOBUFS - The output queue for a network interface is full.
545 // This generally indicates that the interface has stopped sending,
546 // but may be caused by transient congestion.
547 if (GetError() == ENOBUFS) {
548 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000549 }
jbauch095ae152015-12-18 01:39:55 -0800550#endif
551}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000552
jbauch577f5dc2017-05-17 16:32:26 -0700553void PhysicalSocket::SetEnabledEvents(uint8_t events) {
554 enabled_events_ = events;
555}
556
557void PhysicalSocket::EnableEvents(uint8_t events) {
558 enabled_events_ |= events;
559}
560
561void PhysicalSocket::DisableEvents(uint8_t events) {
562 enabled_events_ &= ~events;
563}
564
jbauch095ae152015-12-18 01:39:55 -0800565int PhysicalSocket::TranslateOption(Option opt, int* slevel, int* sopt) {
566 switch (opt) {
567 case OPT_DONTFRAGMENT:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000568#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800569 *slevel = IPPROTO_IP;
570 *sopt = IP_DONTFRAGMENT;
571 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000572#elif defined(WEBRTC_MAC) || defined(BSD) || defined(__native_client__)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100573 RTC_LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
jbauch095ae152015-12-18 01:39:55 -0800574 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000575#elif defined(WEBRTC_POSIX)
jbauch095ae152015-12-18 01:39:55 -0800576 *slevel = IPPROTO_IP;
577 *sopt = IP_MTU_DISCOVER;
578 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000579#endif
jbauch095ae152015-12-18 01:39:55 -0800580 case OPT_RCVBUF:
581 *slevel = SOL_SOCKET;
582 *sopt = SO_RCVBUF;
583 break;
584 case OPT_SNDBUF:
585 *slevel = SOL_SOCKET;
586 *sopt = SO_SNDBUF;
587 break;
588 case OPT_NODELAY:
589 *slevel = IPPROTO_TCP;
590 *sopt = TCP_NODELAY;
591 break;
592 case OPT_DSCP:
Mirko Bonadei675513b2017-11-09 11:09:25 +0100593 RTC_LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
jbauch095ae152015-12-18 01:39:55 -0800594 return -1;
595 case OPT_RTP_SENDTIME_EXTN_ID:
596 return -1; // No logging is necessary as this not a OS socket option.
597 default:
nissec80e7412017-01-11 05:56:46 -0800598 RTC_NOTREACHED();
jbauch095ae152015-12-18 01:39:55 -0800599 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000600 }
jbauch095ae152015-12-18 01:39:55 -0800601 return 0;
602}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000603
jbauch4331fcd2016-01-06 22:20:28 -0800604SocketDispatcher::SocketDispatcher(PhysicalSocketServer *ss)
605#if defined(WEBRTC_WIN)
606 : PhysicalSocket(ss), id_(0), signal_close_(false)
607#else
608 : PhysicalSocket(ss)
609#endif
610{
611}
612
613SocketDispatcher::SocketDispatcher(SOCKET s, PhysicalSocketServer *ss)
614#if defined(WEBRTC_WIN)
615 : PhysicalSocket(ss, s), id_(0), signal_close_(false)
616#else
617 : PhysicalSocket(ss, s)
618#endif
619{
620}
621
622SocketDispatcher::~SocketDispatcher() {
623 Close();
624}
625
626bool SocketDispatcher::Initialize() {
nisseede5da42017-01-12 05:15:36 -0800627 RTC_DCHECK(s_ != INVALID_SOCKET);
jbauch4331fcd2016-01-06 22:20:28 -0800628 // Must be a non-blocking
629#if defined(WEBRTC_WIN)
630 u_long argp = 1;
631 ioctlsocket(s_, FIONBIO, &argp);
632#elif defined(WEBRTC_POSIX)
633 fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
634#endif
deadbeefeae45642017-05-26 16:27:09 -0700635#if defined(WEBRTC_IOS)
636 // iOS may kill sockets when the app is moved to the background
637 // (specifically, if the app doesn't use the "voip" UIBackgroundMode). When
638 // we attempt to write to such a socket, SIGPIPE will be raised, which by
639 // default will terminate the process, which we don't want. By specifying
640 // this socket option, SIGPIPE will be disabled for the socket.
641 int value = 1;
642 ::setsockopt(s_, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value));
643#endif
jbauch4331fcd2016-01-06 22:20:28 -0800644 ss_->Add(this);
645 return true;
646}
647
648bool SocketDispatcher::Create(int type) {
649 return Create(AF_INET, type);
650}
651
652bool SocketDispatcher::Create(int family, int type) {
653 // Change the socket to be non-blocking.
654 if (!PhysicalSocket::Create(family, type))
655 return false;
656
657 if (!Initialize())
658 return false;
659
660#if defined(WEBRTC_WIN)
661 do { id_ = ++next_id_; } while (id_ == 0);
662#endif
663 return true;
664}
665
666#if defined(WEBRTC_WIN)
667
668WSAEVENT SocketDispatcher::GetWSAEvent() {
669 return WSA_INVALID_EVENT;
670}
671
672SOCKET SocketDispatcher::GetSocket() {
673 return s_;
674}
675
676bool SocketDispatcher::CheckSignalClose() {
677 if (!signal_close_)
678 return false;
679
680 char ch;
681 if (recv(s_, &ch, 1, MSG_PEEK) > 0)
682 return false;
683
684 state_ = CS_CLOSED;
685 signal_close_ = false;
686 SignalCloseEvent(this, signal_err_);
687 return true;
688}
689
690int SocketDispatcher::next_id_ = 0;
691
692#elif defined(WEBRTC_POSIX)
693
694int SocketDispatcher::GetDescriptor() {
695 return s_;
696}
697
698bool SocketDispatcher::IsDescriptorClosed() {
deadbeeffaedf7f2017-02-09 15:09:22 -0800699 if (udp_) {
700 // The MSG_PEEK trick doesn't work for UDP, since (at least in some
701 // circumstances) it requires reading an entire UDP packet, which would be
702 // bad for performance here. So, just check whether |s_| has been closed,
703 // which should be sufficient.
704 return s_ == INVALID_SOCKET;
705 }
jbauch4331fcd2016-01-06 22:20:28 -0800706 // We don't have a reliable way of distinguishing end-of-stream
707 // from readability. So test on each readable call. Is this
708 // inefficient? Probably.
709 char ch;
710 ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
711 if (res > 0) {
712 // Data available, so not closed.
713 return false;
714 } else if (res == 0) {
715 // EOF, so closed.
716 return true;
717 } else { // error
718 switch (errno) {
719 // Returned if we've already closed s_.
720 case EBADF:
721 // Returned during ungraceful peer shutdown.
722 case ECONNRESET:
723 return true;
deadbeeffaedf7f2017-02-09 15:09:22 -0800724 // The normal blocking error; don't log anything.
725 case EWOULDBLOCK:
726 // Interrupted system call.
727 case EINTR:
728 return false;
jbauch4331fcd2016-01-06 22:20:28 -0800729 default:
730 // Assume that all other errors are just blocking errors, meaning the
731 // connection is still good but we just can't read from it right now.
732 // This should only happen when connecting (and at most once), because
733 // in all other cases this function is only called if the file
734 // descriptor is already known to be in the readable state. However,
735 // it's not necessary a problem if we spuriously interpret a
736 // "connection lost"-type error as a blocking error, because typically
737 // the next recv() will get EOF, so we'll still eventually notice that
738 // the socket is closed.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100739 RTC_LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
jbauch4331fcd2016-01-06 22:20:28 -0800740 return false;
741 }
742 }
743}
744
745#endif // WEBRTC_POSIX
746
747uint32_t SocketDispatcher::GetRequestedEvents() {
jbauch577f5dc2017-05-17 16:32:26 -0700748 return enabled_events();
jbauch4331fcd2016-01-06 22:20:28 -0800749}
750
751void SocketDispatcher::OnPreEvent(uint32_t ff) {
752 if ((ff & DE_CONNECT) != 0)
753 state_ = CS_CONNECTED;
754
755#if defined(WEBRTC_WIN)
756 // We set CS_CLOSED from CheckSignalClose.
757#elif defined(WEBRTC_POSIX)
758 if ((ff & DE_CLOSE) != 0)
759 state_ = CS_CLOSED;
760#endif
761}
762
763#if defined(WEBRTC_WIN)
764
765void SocketDispatcher::OnEvent(uint32_t ff, int err) {
766 int cache_id = id_;
767 // Make sure we deliver connect/accept first. Otherwise, consumers may see
768 // something like a READ followed by a CONNECT, which would be odd.
769 if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
770 if (ff != DE_CONNECT)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100771 RTC_LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
jbauch577f5dc2017-05-17 16:32:26 -0700772 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800773#if !defined(NDEBUG)
774 dbg_addr_ = "Connected @ ";
775 dbg_addr_.append(GetRemoteAddress().ToString());
776#endif
777 SignalConnectEvent(this);
778 }
779 if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700780 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800781 SignalReadEvent(this);
782 }
783 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700784 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800785 SignalReadEvent(this);
786 }
787 if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700788 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800789 SignalWriteEvent(this);
790 }
791 if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
792 signal_close_ = true;
793 signal_err_ = err;
794 }
795}
796
797#elif defined(WEBRTC_POSIX)
798
799void SocketDispatcher::OnEvent(uint32_t ff, int err) {
jbauchde4db112017-05-31 13:09:18 -0700800#if defined(WEBRTC_USE_EPOLL)
801 // Remember currently enabled events so we can combine multiple changes
802 // into one update call later.
803 // The signal handlers might re-enable events disabled here, so we can't
804 // keep a list of events to disable at the end of the method. This list
805 // would not be updated with the events enabled by the signal handlers.
806 StartBatchedEventUpdates();
807#endif
jbauch4331fcd2016-01-06 22:20:28 -0800808 // Make sure we deliver connect/accept first. Otherwise, consumers may see
809 // something like a READ followed by a CONNECT, which would be odd.
810 if ((ff & DE_CONNECT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700811 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800812 SignalConnectEvent(this);
813 }
814 if ((ff & DE_ACCEPT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700815 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800816 SignalReadEvent(this);
817 }
818 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700819 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800820 SignalReadEvent(this);
821 }
822 if ((ff & DE_WRITE) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700823 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800824 SignalWriteEvent(this);
825 }
826 if ((ff & DE_CLOSE) != 0) {
827 // The socket is now dead to us, so stop checking it.
jbauch577f5dc2017-05-17 16:32:26 -0700828 SetEnabledEvents(0);
jbauch4331fcd2016-01-06 22:20:28 -0800829 SignalCloseEvent(this, err);
830 }
jbauchde4db112017-05-31 13:09:18 -0700831#if defined(WEBRTC_USE_EPOLL)
832 FinishBatchedEventUpdates();
833#endif
jbauch4331fcd2016-01-06 22:20:28 -0800834}
835
836#endif // WEBRTC_POSIX
837
jbauchde4db112017-05-31 13:09:18 -0700838#if defined(WEBRTC_USE_EPOLL)
839
840static int GetEpollEvents(uint32_t ff) {
841 int events = 0;
842 if (ff & (DE_READ | DE_ACCEPT)) {
843 events |= EPOLLIN;
844 }
845 if (ff & (DE_WRITE | DE_CONNECT)) {
846 events |= EPOLLOUT;
847 }
848 return events;
849}
850
851void SocketDispatcher::StartBatchedEventUpdates() {
852 RTC_DCHECK_EQ(saved_enabled_events_, -1);
853 saved_enabled_events_ = enabled_events();
854}
855
856void SocketDispatcher::FinishBatchedEventUpdates() {
857 RTC_DCHECK_NE(saved_enabled_events_, -1);
858 uint8_t old_events = static_cast<uint8_t>(saved_enabled_events_);
859 saved_enabled_events_ = -1;
860 MaybeUpdateDispatcher(old_events);
861}
862
863void SocketDispatcher::MaybeUpdateDispatcher(uint8_t old_events) {
864 if (GetEpollEvents(enabled_events()) != GetEpollEvents(old_events) &&
865 saved_enabled_events_ == -1) {
866 ss_->Update(this);
867 }
868}
869
870void SocketDispatcher::SetEnabledEvents(uint8_t events) {
871 uint8_t old_events = enabled_events();
872 PhysicalSocket::SetEnabledEvents(events);
873 MaybeUpdateDispatcher(old_events);
874}
875
876void SocketDispatcher::EnableEvents(uint8_t events) {
877 uint8_t old_events = enabled_events();
878 PhysicalSocket::EnableEvents(events);
879 MaybeUpdateDispatcher(old_events);
880}
881
882void SocketDispatcher::DisableEvents(uint8_t events) {
883 uint8_t old_events = enabled_events();
884 PhysicalSocket::DisableEvents(events);
885 MaybeUpdateDispatcher(old_events);
886}
887
888#endif // WEBRTC_USE_EPOLL
889
jbauch4331fcd2016-01-06 22:20:28 -0800890int SocketDispatcher::Close() {
891 if (s_ == INVALID_SOCKET)
892 return 0;
893
894#if defined(WEBRTC_WIN)
895 id_ = 0;
896 signal_close_ = false;
897#endif
898 ss_->Remove(this);
899 return PhysicalSocket::Close();
900}
901
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000902#if defined(WEBRTC_POSIX)
903class EventDispatcher : public Dispatcher {
904 public:
905 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
906 if (pipe(afd_) < 0)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100907 RTC_LOG(LERROR) << "pipe failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000908 ss_->Add(this);
909 }
910
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000911 ~EventDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000912 ss_->Remove(this);
913 close(afd_[0]);
914 close(afd_[1]);
915 }
916
917 virtual void Signal() {
918 CritScope cs(&crit_);
919 if (!fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200920 const uint8_t b[1] = {0};
nissec16fa5e2017-02-07 07:18:43 -0800921 const ssize_t res = write(afd_[1], b, sizeof(b));
922 RTC_DCHECK_EQ(1, res);
923 fSignaled_ = true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000924 }
925 }
926
Peter Boström0c4e06b2015-10-07 12:23:21 +0200927 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000928
Peter Boström0c4e06b2015-10-07 12:23:21 +0200929 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000930 // It is not possible to perfectly emulate an auto-resetting event with
931 // pipes. This simulates it by resetting before the event is handled.
932
933 CritScope cs(&crit_);
934 if (fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200935 uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
nissec16fa5e2017-02-07 07:18:43 -0800936 const ssize_t res = read(afd_[0], b, sizeof(b));
937 RTC_DCHECK_EQ(1, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000938 fSignaled_ = false;
939 }
940 }
941
nissec80e7412017-01-11 05:56:46 -0800942 void OnEvent(uint32_t ff, int err) override { RTC_NOTREACHED(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000943
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000944 int GetDescriptor() override { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000945
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000946 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000947
948 private:
949 PhysicalSocketServer *ss_;
950 int afd_[2];
951 bool fSignaled_;
952 CriticalSection crit_;
953};
954
955// These two classes use the self-pipe trick to deliver POSIX signals to our
956// select loop. This is the only safe, reliable, cross-platform way to do
957// non-trivial things with a POSIX signal in an event-driven program (until
958// proper pselect() implementations become ubiquitous).
959
960class PosixSignalHandler {
961 public:
962 // POSIX only specifies 32 signals, but in principle the system might have
963 // more and the programmer might choose to use them, so we size our array
964 // for 128.
965 static const int kNumPosixSignals = 128;
966
967 // There is just a single global instance. (Signal handlers do not get any
968 // sort of user-defined void * parameter, so they can't access anything that
969 // isn't global.)
970 static PosixSignalHandler* Instance() {
Andrew MacDonald469c2c02015-05-22 17:50:26 -0700971 RTC_DEFINE_STATIC_LOCAL(PosixSignalHandler, instance, ());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000972 return &instance;
973 }
974
975 // Returns true if the given signal number is set.
976 bool IsSignalSet(int signum) const {
nisseede5da42017-01-12 05:15:36 -0800977 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800978 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000979 return received_signal_[signum];
980 } else {
981 return false;
982 }
983 }
984
985 // Clears the given signal number.
986 void ClearSignal(int signum) {
nisseede5da42017-01-12 05:15:36 -0800987 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800988 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000989 received_signal_[signum] = false;
990 }
991 }
992
993 // Returns the file descriptor to monitor for signal events.
994 int GetDescriptor() const {
995 return afd_[0];
996 }
997
998 // This is called directly from our real signal handler, so it must be
999 // signal-handler-safe. That means it cannot assume anything about the
1000 // user-level state of the process, since the handler could be executed at any
1001 // time on any thread.
1002 void OnPosixSignalReceived(int signum) {
tfarina5237aaf2015-11-10 23:44:30 -08001003 if (signum >= static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001004 // We don't have space in our array for this.
1005 return;
1006 }
1007 // Set a flag saying we've seen this signal.
1008 received_signal_[signum] = true;
1009 // Notify application code that we got a signal.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001010 const uint8_t b[1] = {0};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001011 if (-1 == write(afd_[1], b, sizeof(b))) {
1012 // Nothing we can do here. If there's an error somehow then there's
1013 // nothing we can safely do from a signal handler.
1014 // No, we can't even safely log it.
1015 // But, we still have to check the return value here. Otherwise,
1016 // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
1017 return;
1018 }
1019 }
1020
1021 private:
1022 PosixSignalHandler() {
1023 if (pipe(afd_) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001024 RTC_LOG_ERR(LS_ERROR) << "pipe failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001025 return;
1026 }
1027 if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001028 RTC_LOG_ERR(LS_WARNING) << "fcntl #1 failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001029 }
1030 if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001031 RTC_LOG_ERR(LS_WARNING) << "fcntl #2 failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001032 }
1033 memset(const_cast<void *>(static_cast<volatile void *>(received_signal_)),
1034 0,
1035 sizeof(received_signal_));
1036 }
1037
1038 ~PosixSignalHandler() {
1039 int fd1 = afd_[0];
1040 int fd2 = afd_[1];
1041 // We clobber the stored file descriptor numbers here or else in principle
1042 // a signal that happens to be delivered during application termination
1043 // could erroneously write a zero byte to an unrelated file handle in
1044 // OnPosixSignalReceived() if some other file happens to be opened later
1045 // during shutdown and happens to be given the same file descriptor number
1046 // as our pipe had. Unfortunately even with this precaution there is still a
1047 // race where that could occur if said signal happens to be handled
1048 // concurrently with this code and happens to have already read the value of
1049 // afd_[1] from memory before we clobber it, but that's unlikely.
1050 afd_[0] = -1;
1051 afd_[1] = -1;
1052 close(fd1);
1053 close(fd2);
1054 }
1055
1056 int afd_[2];
1057 // These are boolean flags that will be set in our signal handler and read
1058 // and cleared from Wait(). There is a race involved in this, but it is
1059 // benign. The signal handler sets the flag before signaling the pipe, so
1060 // we'll never end up blocking in select() while a flag is still true.
1061 // However, if two of the same signal arrive close to each other then it's
1062 // possible that the second time the handler may set the flag while it's still
1063 // true, meaning that signal will be missed. But the first occurrence of it
1064 // will still be handled, so this isn't a problem.
1065 // Volatile is not necessary here for correctness, but this data _is_ volatile
1066 // so I've marked it as such.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001067 volatile uint8_t received_signal_[kNumPosixSignals];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001068};
1069
1070class PosixSignalDispatcher : public Dispatcher {
1071 public:
1072 PosixSignalDispatcher(PhysicalSocketServer *owner) : owner_(owner) {
1073 owner_->Add(this);
1074 }
1075
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001076 ~PosixSignalDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001077 owner_->Remove(this);
1078 }
1079
Peter Boström0c4e06b2015-10-07 12:23:21 +02001080 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001081
Peter Boström0c4e06b2015-10-07 12:23:21 +02001082 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001083 // Events might get grouped if signals come very fast, so we read out up to
1084 // 16 bytes to make sure we keep the pipe empty.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001085 uint8_t b[16];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001086 ssize_t ret = read(GetDescriptor(), b, sizeof(b));
1087 if (ret < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001088 RTC_LOG_ERR(LS_WARNING) << "Error in read()";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001089 } else if (ret == 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001090 RTC_LOG(LS_WARNING) << "Should have read at least one byte";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001091 }
1092 }
1093
Peter Boström0c4e06b2015-10-07 12:23:21 +02001094 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001095 for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
1096 ++signum) {
1097 if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
1098 PosixSignalHandler::Instance()->ClearSignal(signum);
1099 HandlerMap::iterator i = handlers_.find(signum);
1100 if (i == handlers_.end()) {
1101 // This can happen if a signal is delivered to our process at around
1102 // the same time as we unset our handler for it. It is not an error
1103 // condition, but it's unusual enough to be worth logging.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001104 RTC_LOG(LS_INFO) << "Received signal with no handler: " << signum;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001105 } else {
1106 // Otherwise, execute our handler.
1107 (*i->second)(signum);
1108 }
1109 }
1110 }
1111 }
1112
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001113 int GetDescriptor() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001114 return PosixSignalHandler::Instance()->GetDescriptor();
1115 }
1116
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001117 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001118
1119 void SetHandler(int signum, void (*handler)(int)) {
1120 handlers_[signum] = handler;
1121 }
1122
1123 void ClearHandler(int signum) {
1124 handlers_.erase(signum);
1125 }
1126
1127 bool HasHandlers() {
1128 return !handlers_.empty();
1129 }
1130
1131 private:
1132 typedef std::map<int, void (*)(int)> HandlerMap;
1133
1134 HandlerMap handlers_;
1135 // Our owner.
1136 PhysicalSocketServer *owner_;
1137};
1138
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001139#endif // WEBRTC_POSIX
1140
1141#if defined(WEBRTC_WIN)
Peter Boström0c4e06b2015-10-07 12:23:21 +02001142static uint32_t FlagsToEvents(uint32_t events) {
1143 uint32_t ffFD = FD_CLOSE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001144 if (events & DE_READ)
1145 ffFD |= FD_READ;
1146 if (events & DE_WRITE)
1147 ffFD |= FD_WRITE;
1148 if (events & DE_CONNECT)
1149 ffFD |= FD_CONNECT;
1150 if (events & DE_ACCEPT)
1151 ffFD |= FD_ACCEPT;
1152 return ffFD;
1153}
1154
1155class EventDispatcher : public Dispatcher {
1156 public:
1157 EventDispatcher(PhysicalSocketServer *ss) : ss_(ss) {
1158 hev_ = WSACreateEvent();
1159 if (hev_) {
1160 ss_->Add(this);
1161 }
1162 }
1163
Steve Anton9de3aac2017-10-24 10:08:26 -07001164 ~EventDispatcher() override {
deadbeef37f5ecf2017-02-27 14:06:41 -08001165 if (hev_ != nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001166 ss_->Remove(this);
1167 WSACloseEvent(hev_);
deadbeef37f5ecf2017-02-27 14:06:41 -08001168 hev_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001169 }
1170 }
1171
1172 virtual void Signal() {
deadbeef37f5ecf2017-02-27 14:06:41 -08001173 if (hev_ != nullptr)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001174 WSASetEvent(hev_);
1175 }
1176
Steve Anton9de3aac2017-10-24 10:08:26 -07001177 uint32_t GetRequestedEvents() override { return 0; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001178
Steve Anton9de3aac2017-10-24 10:08:26 -07001179 void OnPreEvent(uint32_t ff) override { WSAResetEvent(hev_); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001180
Steve Anton9de3aac2017-10-24 10:08:26 -07001181 void OnEvent(uint32_t ff, int err) override {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001182
Steve Anton9de3aac2017-10-24 10:08:26 -07001183 WSAEVENT GetWSAEvent() override { return hev_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001184
Steve Anton9de3aac2017-10-24 10:08:26 -07001185 SOCKET GetSocket() override { return INVALID_SOCKET; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001186
Steve Anton9de3aac2017-10-24 10:08:26 -07001187 bool CheckSignalClose() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001188
Steve Anton9de3aac2017-10-24 10:08:26 -07001189 private:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001190 PhysicalSocketServer* ss_;
1191 WSAEVENT hev_;
1192};
honghaizcec0a082016-01-15 14:49:09 -08001193#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001194
1195// Sets the value of a boolean value to false when signaled.
1196class Signaler : public EventDispatcher {
1197 public:
1198 Signaler(PhysicalSocketServer* ss, bool* pf)
1199 : EventDispatcher(ss), pf_(pf) {
1200 }
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001201 ~Signaler() override { }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001202
Peter Boström0c4e06b2015-10-07 12:23:21 +02001203 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001204 if (pf_)
1205 *pf_ = false;
1206 }
1207
1208 private:
1209 bool *pf_;
1210};
1211
1212PhysicalSocketServer::PhysicalSocketServer()
1213 : fWait_(false) {
jbauchde4db112017-05-31 13:09:18 -07001214#if defined(WEBRTC_USE_EPOLL)
1215 // Since Linux 2.6.8, the size argument is ignored, but must be greater than
1216 // zero. Before that the size served as hint to the kernel for the amount of
1217 // space to initially allocate in internal data structures.
1218 epoll_fd_ = epoll_create(FD_SETSIZE);
1219 if (epoll_fd_ == -1) {
1220 // Not an error, will fall back to "select" below.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001221 RTC_LOG_E(LS_WARNING, EN, errno) << "epoll_create";
jbauchde4db112017-05-31 13:09:18 -07001222 epoll_fd_ = INVALID_SOCKET;
1223 }
1224#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001225 signal_wakeup_ = new Signaler(this, &fWait_);
1226#if defined(WEBRTC_WIN)
1227 socket_ev_ = WSACreateEvent();
1228#endif
1229}
1230
1231PhysicalSocketServer::~PhysicalSocketServer() {
1232#if defined(WEBRTC_WIN)
1233 WSACloseEvent(socket_ev_);
1234#endif
1235#if defined(WEBRTC_POSIX)
1236 signal_dispatcher_.reset();
1237#endif
1238 delete signal_wakeup_;
jbauchde4db112017-05-31 13:09:18 -07001239#if defined(WEBRTC_USE_EPOLL)
1240 if (epoll_fd_ != INVALID_SOCKET) {
1241 close(epoll_fd_);
1242 }
1243#endif
nisseede5da42017-01-12 05:15:36 -08001244 RTC_DCHECK(dispatchers_.empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001245}
1246
1247void PhysicalSocketServer::WakeUp() {
1248 signal_wakeup_->Signal();
1249}
1250
1251Socket* PhysicalSocketServer::CreateSocket(int type) {
1252 return CreateSocket(AF_INET, type);
1253}
1254
1255Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
1256 PhysicalSocket* socket = new PhysicalSocket(this);
1257 if (socket->Create(family, type)) {
1258 return socket;
1259 } else {
1260 delete socket;
jbauch095ae152015-12-18 01:39:55 -08001261 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001262 }
1263}
1264
1265AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int type) {
1266 return CreateAsyncSocket(AF_INET, type);
1267}
1268
1269AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
1270 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1271 if (dispatcher->Create(family, type)) {
1272 return dispatcher;
1273 } else {
1274 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001275 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001276 }
1277}
1278
1279AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
1280 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1281 if (dispatcher->Initialize()) {
1282 return dispatcher;
1283 } else {
1284 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001285 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001286 }
1287}
1288
1289void PhysicalSocketServer::Add(Dispatcher *pdispatcher) {
1290 CritScope cs(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001291 if (processing_dispatchers_) {
1292 // A dispatcher is being added while a "Wait" call is processing the
1293 // list of socket events.
1294 // Defer adding to "dispatchers_" set until processing is done to avoid
1295 // invalidating the iterator in "Wait".
1296 pending_remove_dispatchers_.erase(pdispatcher);
1297 pending_add_dispatchers_.insert(pdispatcher);
1298 } else {
1299 dispatchers_.insert(pdispatcher);
1300 }
1301#if defined(WEBRTC_USE_EPOLL)
1302 if (epoll_fd_ != INVALID_SOCKET) {
1303 AddEpoll(pdispatcher);
1304 }
1305#endif // WEBRTC_USE_EPOLL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001306}
1307
1308void PhysicalSocketServer::Remove(Dispatcher *pdispatcher) {
1309 CritScope cs(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001310 if (processing_dispatchers_) {
1311 // A dispatcher is being removed while a "Wait" call is processing the
1312 // list of socket events.
1313 // Defer removal from "dispatchers_" set until processing is done to avoid
1314 // invalidating the iterator in "Wait".
1315 if (!pending_add_dispatchers_.erase(pdispatcher) &&
1316 dispatchers_.find(pdispatcher) == dispatchers_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001317 RTC_LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
1318 << "dispatcher, potentially from a duplicate call to "
1319 << "Add.";
jbauchde4db112017-05-31 13:09:18 -07001320 return;
1321 }
1322
1323 pending_remove_dispatchers_.insert(pdispatcher);
1324 } else if (!dispatchers_.erase(pdispatcher)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001325 RTC_LOG(LS_WARNING)
1326 << "PhysicalSocketServer asked to remove a unknown "
1327 << "dispatcher, potentially from a duplicate call to Add.";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001328 return;
1329 }
jbauchde4db112017-05-31 13:09:18 -07001330#if defined(WEBRTC_USE_EPOLL)
1331 if (epoll_fd_ != INVALID_SOCKET) {
1332 RemoveEpoll(pdispatcher);
1333 }
1334#endif // WEBRTC_USE_EPOLL
1335}
1336
1337void PhysicalSocketServer::Update(Dispatcher* pdispatcher) {
1338#if defined(WEBRTC_USE_EPOLL)
1339 if (epoll_fd_ == INVALID_SOCKET) {
1340 return;
1341 }
1342
1343 CritScope cs(&crit_);
1344 if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1345 return;
1346 }
1347
1348 UpdateEpoll(pdispatcher);
1349#endif
1350}
1351
1352void PhysicalSocketServer::AddRemovePendingDispatchers() {
1353 if (!pending_add_dispatchers_.empty()) {
1354 for (Dispatcher* pdispatcher : pending_add_dispatchers_) {
1355 dispatchers_.insert(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001356 }
jbauchde4db112017-05-31 13:09:18 -07001357 pending_add_dispatchers_.clear();
1358 }
1359
1360 if (!pending_remove_dispatchers_.empty()) {
1361 for (Dispatcher* pdispatcher : pending_remove_dispatchers_) {
1362 dispatchers_.erase(pdispatcher);
1363 }
1364 pending_remove_dispatchers_.clear();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001365 }
1366}
1367
1368#if defined(WEBRTC_POSIX)
jbauchde4db112017-05-31 13:09:18 -07001369
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001370bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
jbauchde4db112017-05-31 13:09:18 -07001371#if defined(WEBRTC_USE_EPOLL)
1372 // We don't keep a dedicated "epoll" descriptor containing only the non-IO
1373 // (i.e. signaling) dispatcher, so "poll" will be used instead of the default
1374 // "select" to support sockets larger than FD_SETSIZE.
1375 if (!process_io) {
1376 return WaitPoll(cmsWait, signal_wakeup_);
1377 } else if (epoll_fd_ != INVALID_SOCKET) {
1378 return WaitEpoll(cmsWait);
1379 }
1380#endif
1381 return WaitSelect(cmsWait, process_io);
1382}
1383
1384static void ProcessEvents(Dispatcher* dispatcher,
1385 bool readable,
1386 bool writable,
1387 bool check_error) {
1388 int errcode = 0;
1389 // TODO(pthatcher): Should we set errcode if getsockopt fails?
1390 if (check_error) {
1391 socklen_t len = sizeof(errcode);
1392 ::getsockopt(dispatcher->GetDescriptor(), SOL_SOCKET, SO_ERROR, &errcode,
1393 &len);
1394 }
1395
1396 uint32_t ff = 0;
1397
1398 // Check readable descriptors. If we're waiting on an accept, signal
1399 // that. Otherwise we're waiting for data, check to see if we're
1400 // readable or really closed.
1401 // TODO(pthatcher): Only peek at TCP descriptors.
1402 if (readable) {
1403 if (dispatcher->GetRequestedEvents() & DE_ACCEPT) {
1404 ff |= DE_ACCEPT;
1405 } else if (errcode || dispatcher->IsDescriptorClosed()) {
1406 ff |= DE_CLOSE;
1407 } else {
1408 ff |= DE_READ;
1409 }
1410 }
1411
1412 // Check writable descriptors. If we're waiting on a connect, detect
1413 // success versus failure by the reaped error code.
1414 if (writable) {
1415 if (dispatcher->GetRequestedEvents() & DE_CONNECT) {
1416 if (!errcode) {
1417 ff |= DE_CONNECT;
1418 } else {
1419 ff |= DE_CLOSE;
1420 }
1421 } else {
1422 ff |= DE_WRITE;
1423 }
1424 }
1425
1426 // Tell the descriptor about the event.
1427 if (ff != 0) {
1428 dispatcher->OnPreEvent(ff);
1429 dispatcher->OnEvent(ff, errcode);
1430 }
1431}
1432
1433bool PhysicalSocketServer::WaitSelect(int cmsWait, bool process_io) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001434 // Calculate timing information
1435
deadbeef37f5ecf2017-02-27 14:06:41 -08001436 struct timeval* ptvWait = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001437 struct timeval tvWait;
1438 struct timeval tvStop;
1439 if (cmsWait != kForever) {
1440 // Calculate wait timeval
1441 tvWait.tv_sec = cmsWait / 1000;
1442 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1443 ptvWait = &tvWait;
1444
1445 // Calculate when to return in a timeval
deadbeef37f5ecf2017-02-27 14:06:41 -08001446 gettimeofday(&tvStop, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001447 tvStop.tv_sec += tvWait.tv_sec;
1448 tvStop.tv_usec += tvWait.tv_usec;
1449 if (tvStop.tv_usec >= 1000000) {
1450 tvStop.tv_usec -= 1000000;
1451 tvStop.tv_sec += 1;
1452 }
1453 }
1454
1455 // Zero all fd_sets. Don't need to do this inside the loop since
1456 // select() zeros the descriptors not signaled
1457
1458 fd_set fdsRead;
1459 FD_ZERO(&fdsRead);
1460 fd_set fdsWrite;
1461 FD_ZERO(&fdsWrite);
pbos@webrtc.org27e58982014-10-07 17:56:53 +00001462 // Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1463 // inline assembly in FD_ZERO.
1464 // http://crbug.com/344505
1465#ifdef MEMORY_SANITIZER
1466 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1467 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1468#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001469
1470 fWait_ = true;
1471
1472 while (fWait_) {
1473 int fdmax = -1;
1474 {
1475 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001476 // TODO(jbauch): Support re-entrant waiting.
1477 RTC_DCHECK(!processing_dispatchers_);
1478 for (Dispatcher* pdispatcher : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001479 // Query dispatchers for read and write wait state
nisseede5da42017-01-12 05:15:36 -08001480 RTC_DCHECK(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001481 if (!process_io && (pdispatcher != signal_wakeup_))
1482 continue;
1483 int fd = pdispatcher->GetDescriptor();
jbauchde4db112017-05-31 13:09:18 -07001484 // "select"ing a file descriptor that is equal to or larger than
1485 // FD_SETSIZE will result in undefined behavior.
1486 RTC_DCHECK_LT(fd, FD_SETSIZE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001487 if (fd > fdmax)
1488 fdmax = fd;
1489
Peter Boström0c4e06b2015-10-07 12:23:21 +02001490 uint32_t ff = pdispatcher->GetRequestedEvents();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001491 if (ff & (DE_READ | DE_ACCEPT))
1492 FD_SET(fd, &fdsRead);
1493 if (ff & (DE_WRITE | DE_CONNECT))
1494 FD_SET(fd, &fdsWrite);
1495 }
1496 }
1497
1498 // Wait then call handlers as appropriate
1499 // < 0 means error
1500 // 0 means timeout
1501 // > 0 means count of descriptors ready
deadbeef37f5ecf2017-02-27 14:06:41 -08001502 int n = select(fdmax + 1, &fdsRead, &fdsWrite, nullptr, ptvWait);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001503
1504 // If error, return error.
1505 if (n < 0) {
1506 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001507 RTC_LOG_E(LS_ERROR, EN, errno) << "select";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001508 return false;
1509 }
1510 // Else ignore the error and keep going. If this EINTR was for one of the
1511 // signals managed by this PhysicalSocketServer, the
1512 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1513 // iteration.
1514 } else if (n == 0) {
1515 // If timeout, return success
1516 return true;
1517 } else {
1518 // We have signaled descriptors
1519 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001520 processing_dispatchers_ = true;
1521 for (Dispatcher* pdispatcher : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001522 int fd = pdispatcher->GetDescriptor();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001523
jbauchde4db112017-05-31 13:09:18 -07001524 bool readable = FD_ISSET(fd, &fdsRead);
1525 if (readable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001526 FD_CLR(fd, &fdsRead);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001527 }
1528
jbauchde4db112017-05-31 13:09:18 -07001529 bool writable = FD_ISSET(fd, &fdsWrite);
1530 if (writable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001531 FD_CLR(fd, &fdsWrite);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001532 }
1533
jbauchde4db112017-05-31 13:09:18 -07001534 // The error code can be signaled through reads or writes.
1535 ProcessEvents(pdispatcher, readable, writable, readable || writable);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001536 }
jbauchde4db112017-05-31 13:09:18 -07001537
1538 processing_dispatchers_ = false;
1539 // Process deferred dispatchers that have been added/removed while the
1540 // events were handled above.
1541 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001542 }
1543
1544 // Recalc the time remaining to wait. Doing it here means it doesn't get
1545 // calced twice the first time through the loop
1546 if (ptvWait) {
1547 ptvWait->tv_sec = 0;
1548 ptvWait->tv_usec = 0;
1549 struct timeval tvT;
deadbeef37f5ecf2017-02-27 14:06:41 -08001550 gettimeofday(&tvT, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001551 if ((tvStop.tv_sec > tvT.tv_sec)
1552 || ((tvStop.tv_sec == tvT.tv_sec)
1553 && (tvStop.tv_usec > tvT.tv_usec))) {
1554 ptvWait->tv_sec = tvStop.tv_sec - tvT.tv_sec;
1555 ptvWait->tv_usec = tvStop.tv_usec - tvT.tv_usec;
1556 if (ptvWait->tv_usec < 0) {
nisseede5da42017-01-12 05:15:36 -08001557 RTC_DCHECK(ptvWait->tv_sec > 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001558 ptvWait->tv_usec += 1000000;
1559 ptvWait->tv_sec -= 1;
1560 }
1561 }
1562 }
1563 }
1564
1565 return true;
1566}
1567
jbauchde4db112017-05-31 13:09:18 -07001568#if defined(WEBRTC_USE_EPOLL)
1569
1570// Initial number of events to process with one call to "epoll_wait".
1571static const size_t kInitialEpollEvents = 128;
1572
1573// Maximum number of events to process with one call to "epoll_wait".
1574static const size_t kMaxEpollEvents = 8192;
1575
1576void PhysicalSocketServer::AddEpoll(Dispatcher* pdispatcher) {
1577 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1578 int fd = pdispatcher->GetDescriptor();
1579 RTC_DCHECK(fd != INVALID_SOCKET);
1580 if (fd == INVALID_SOCKET) {
1581 return;
1582 }
1583
1584 struct epoll_event event = {0};
1585 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
1586 event.data.ptr = pdispatcher;
1587 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &event);
1588 RTC_DCHECK_EQ(err, 0);
1589 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001590 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_ADD";
jbauchde4db112017-05-31 13:09:18 -07001591 }
1592}
1593
1594void PhysicalSocketServer::RemoveEpoll(Dispatcher* pdispatcher) {
1595 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1596 int fd = pdispatcher->GetDescriptor();
1597 RTC_DCHECK(fd != INVALID_SOCKET);
1598 if (fd == INVALID_SOCKET) {
1599 return;
1600 }
1601
1602 struct epoll_event event = {0};
1603 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &event);
1604 RTC_DCHECK(err == 0 || errno == ENOENT);
1605 if (err == -1) {
1606 if (errno == ENOENT) {
1607 // Socket has already been closed.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001608 RTC_LOG_E(LS_VERBOSE, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001609 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001610 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001611 }
1612 }
1613}
1614
1615void PhysicalSocketServer::UpdateEpoll(Dispatcher* pdispatcher) {
1616 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1617 int fd = pdispatcher->GetDescriptor();
1618 RTC_DCHECK(fd != INVALID_SOCKET);
1619 if (fd == INVALID_SOCKET) {
1620 return;
1621 }
1622
1623 struct epoll_event event = {0};
1624 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
1625 event.data.ptr = pdispatcher;
1626 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &event);
1627 RTC_DCHECK_EQ(err, 0);
1628 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001629 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_MOD";
jbauchde4db112017-05-31 13:09:18 -07001630 }
1631}
1632
1633bool PhysicalSocketServer::WaitEpoll(int cmsWait) {
1634 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1635 int64_t tvWait = -1;
1636 int64_t tvStop = -1;
1637 if (cmsWait != kForever) {
1638 tvWait = cmsWait;
1639 tvStop = TimeAfter(cmsWait);
1640 }
1641
1642 if (epoll_events_.empty()) {
1643 // The initial space to receive events is created only if epoll is used.
1644 epoll_events_.resize(kInitialEpollEvents);
1645 }
1646
1647 fWait_ = true;
1648
1649 while (fWait_) {
1650 // Wait then call handlers as appropriate
1651 // < 0 means error
1652 // 0 means timeout
1653 // > 0 means count of descriptors ready
1654 int n = epoll_wait(epoll_fd_, &epoll_events_[0],
1655 static_cast<int>(epoll_events_.size()),
1656 static_cast<int>(tvWait));
1657 if (n < 0) {
1658 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001659 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll";
jbauchde4db112017-05-31 13:09:18 -07001660 return false;
1661 }
1662 // Else ignore the error and keep going. If this EINTR was for one of the
1663 // signals managed by this PhysicalSocketServer, the
1664 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1665 // iteration.
1666 } else if (n == 0) {
1667 // If timeout, return success
1668 return true;
1669 } else {
1670 // We have signaled descriptors
1671 CritScope cr(&crit_);
1672 for (int i = 0; i < n; ++i) {
1673 const epoll_event& event = epoll_events_[i];
1674 Dispatcher* pdispatcher = static_cast<Dispatcher*>(event.data.ptr);
1675 if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1676 // The dispatcher for this socket no longer exists.
1677 continue;
1678 }
1679
1680 bool readable = (event.events & (EPOLLIN | EPOLLPRI));
1681 bool writable = (event.events & EPOLLOUT);
1682 bool check_error = (event.events & (EPOLLRDHUP | EPOLLERR | EPOLLHUP));
1683
1684 ProcessEvents(pdispatcher, readable, writable, check_error);
1685 }
1686 }
1687
1688 if (static_cast<size_t>(n) == epoll_events_.size() &&
1689 epoll_events_.size() < kMaxEpollEvents) {
1690 // We used the complete space to receive events, increase size for future
1691 // iterations.
1692 epoll_events_.resize(std::max(epoll_events_.size() * 2, kMaxEpollEvents));
1693 }
1694
1695 if (cmsWait != kForever) {
1696 tvWait = TimeDiff(tvStop, TimeMillis());
1697 if (tvWait < 0) {
1698 // Return success on timeout.
1699 return true;
1700 }
1701 }
1702 }
1703
1704 return true;
1705}
1706
1707bool PhysicalSocketServer::WaitPoll(int cmsWait, Dispatcher* dispatcher) {
1708 RTC_DCHECK(dispatcher);
1709 int64_t tvWait = -1;
1710 int64_t tvStop = -1;
1711 if (cmsWait != kForever) {
1712 tvWait = cmsWait;
1713 tvStop = TimeAfter(cmsWait);
1714 }
1715
1716 fWait_ = true;
1717
1718 struct pollfd fds = {0};
1719 int fd = dispatcher->GetDescriptor();
1720 fds.fd = fd;
1721
1722 while (fWait_) {
1723 uint32_t ff = dispatcher->GetRequestedEvents();
1724 fds.events = 0;
1725 if (ff & (DE_READ | DE_ACCEPT)) {
1726 fds.events |= POLLIN;
1727 }
1728 if (ff & (DE_WRITE | DE_CONNECT)) {
1729 fds.events |= POLLOUT;
1730 }
1731 fds.revents = 0;
1732
1733 // Wait then call handlers as appropriate
1734 // < 0 means error
1735 // 0 means timeout
1736 // > 0 means count of descriptors ready
1737 int n = poll(&fds, 1, static_cast<int>(tvWait));
1738 if (n < 0) {
1739 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001740 RTC_LOG_E(LS_ERROR, EN, errno) << "poll";
jbauchde4db112017-05-31 13:09:18 -07001741 return false;
1742 }
1743 // Else ignore the error and keep going. If this EINTR was for one of the
1744 // signals managed by this PhysicalSocketServer, the
1745 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1746 // iteration.
1747 } else if (n == 0) {
1748 // If timeout, return success
1749 return true;
1750 } else {
1751 // We have signaled descriptors (should only be the passed dispatcher).
1752 RTC_DCHECK_EQ(n, 1);
1753 RTC_DCHECK_EQ(fds.fd, fd);
1754
1755 bool readable = (fds.revents & (POLLIN | POLLPRI));
1756 bool writable = (fds.revents & POLLOUT);
1757 bool check_error = (fds.revents & (POLLRDHUP | POLLERR | POLLHUP));
1758
1759 ProcessEvents(dispatcher, readable, writable, check_error);
1760 }
1761
1762 if (cmsWait != kForever) {
1763 tvWait = TimeDiff(tvStop, TimeMillis());
1764 if (tvWait < 0) {
1765 // Return success on timeout.
1766 return true;
1767 }
1768 }
1769 }
1770
1771 return true;
1772}
1773
1774#endif // WEBRTC_USE_EPOLL
1775
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001776static void GlobalSignalHandler(int signum) {
1777 PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
1778}
1779
1780bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
1781 void (*handler)(int)) {
1782 // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
1783 // otherwise set one.
1784 if (handler == SIG_IGN || handler == SIG_DFL) {
1785 if (!InstallSignal(signum, handler)) {
1786 return false;
1787 }
1788 if (signal_dispatcher_) {
1789 signal_dispatcher_->ClearHandler(signum);
1790 if (!signal_dispatcher_->HasHandlers()) {
1791 signal_dispatcher_.reset();
1792 }
1793 }
1794 } else {
1795 if (!signal_dispatcher_) {
1796 signal_dispatcher_.reset(new PosixSignalDispatcher(this));
1797 }
1798 signal_dispatcher_->SetHandler(signum, handler);
1799 if (!InstallSignal(signum, &GlobalSignalHandler)) {
1800 return false;
1801 }
1802 }
1803 return true;
1804}
1805
1806Dispatcher* PhysicalSocketServer::signal_dispatcher() {
1807 return signal_dispatcher_.get();
1808}
1809
1810bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
1811 struct sigaction act;
1812 // It doesn't really matter what we set this mask to.
1813 if (sigemptyset(&act.sa_mask) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001814 RTC_LOG_ERR(LS_ERROR) << "Couldn't set mask";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001815 return false;
1816 }
1817 act.sa_handler = handler;
1818#if !defined(__native_client__)
1819 // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
1820 // and it's a nuisance. Though some syscalls still return EINTR and there's no
1821 // real standard for which ones. :(
1822 act.sa_flags = SA_RESTART;
1823#else
1824 act.sa_flags = 0;
1825#endif
deadbeef37f5ecf2017-02-27 14:06:41 -08001826 if (sigaction(signum, &act, nullptr) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001827 RTC_LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001828 return false;
1829 }
1830 return true;
1831}
1832#endif // WEBRTC_POSIX
1833
1834#if defined(WEBRTC_WIN)
1835bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
Honghai Zhang82d78622016-05-06 11:29:15 -07001836 int64_t cmsTotal = cmsWait;
1837 int64_t cmsElapsed = 0;
1838 int64_t msStart = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001839
1840 fWait_ = true;
1841 while (fWait_) {
1842 std::vector<WSAEVENT> events;
1843 std::vector<Dispatcher *> event_owners;
1844
1845 events.push_back(socket_ev_);
1846
1847 {
1848 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001849 // TODO(jbauch): Support re-entrant waiting.
1850 RTC_DCHECK(!processing_dispatchers_);
1851
1852 // Calling "CheckSignalClose" might remove a closed dispatcher from the
1853 // set. This must be deferred to prevent invalidating the iterator.
1854 processing_dispatchers_ = true;
1855 for (Dispatcher* disp : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001856 if (!process_io && (disp != signal_wakeup_))
1857 continue;
1858 SOCKET s = disp->GetSocket();
1859 if (disp->CheckSignalClose()) {
1860 // We just signalled close, don't poll this socket
1861 } else if (s != INVALID_SOCKET) {
1862 WSAEventSelect(s,
1863 events[0],
1864 FlagsToEvents(disp->GetRequestedEvents()));
1865 } else {
1866 events.push_back(disp->GetWSAEvent());
1867 event_owners.push_back(disp);
1868 }
1869 }
jbauchde4db112017-05-31 13:09:18 -07001870
1871 processing_dispatchers_ = false;
1872 // Process deferred dispatchers that have been added/removed while the
1873 // events were handled above.
1874 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001875 }
1876
1877 // Which is shorter, the delay wait or the asked wait?
1878
Honghai Zhang82d78622016-05-06 11:29:15 -07001879 int64_t cmsNext;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001880 if (cmsWait == kForever) {
1881 cmsNext = cmsWait;
1882 } else {
Honghai Zhang82d78622016-05-06 11:29:15 -07001883 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001884 }
1885
1886 // Wait for one of the events to signal
1887 DWORD dw = WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()),
1888 &events[0],
1889 false,
Honghai Zhang82d78622016-05-06 11:29:15 -07001890 static_cast<DWORD>(cmsNext),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001891 false);
1892
1893 if (dw == WSA_WAIT_FAILED) {
1894 // Failed?
jbauch095ae152015-12-18 01:39:55 -08001895 // TODO(pthatcher): need a better strategy than this!
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001896 WSAGetLastError();
nissec80e7412017-01-11 05:56:46 -08001897 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001898 return false;
1899 } else if (dw == WSA_WAIT_TIMEOUT) {
1900 // Timeout?
1901 return true;
1902 } else {
1903 // Figure out which one it is and call it
1904 CritScope cr(&crit_);
1905 int index = dw - WSA_WAIT_EVENT_0;
1906 if (index > 0) {
1907 --index; // The first event is the socket event
jbauchde4db112017-05-31 13:09:18 -07001908 Dispatcher* disp = event_owners[index];
1909 // The dispatcher could have been removed while waiting for events.
1910 if (dispatchers_.find(disp) != dispatchers_.end()) {
1911 disp->OnPreEvent(0);
1912 disp->OnEvent(0, 0);
1913 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001914 } else if (process_io) {
jbauchde4db112017-05-31 13:09:18 -07001915 processing_dispatchers_ = true;
1916 for (Dispatcher* disp : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001917 SOCKET s = disp->GetSocket();
1918 if (s == INVALID_SOCKET)
1919 continue;
1920
1921 WSANETWORKEVENTS wsaEvents;
1922 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1923 if (err == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001924 {
1925 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1926 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001927 RTC_LOG(WARNING)
1928 << "PhysicalSocketServer got FD_READ_BIT error "
1929 << wsaEvents.iErrorCode[FD_READ_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001930 }
1931 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1932 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001933 RTC_LOG(WARNING)
1934 << "PhysicalSocketServer got FD_WRITE_BIT error "
1935 << wsaEvents.iErrorCode[FD_WRITE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001936 }
1937 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1938 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001939 RTC_LOG(WARNING)
1940 << "PhysicalSocketServer got FD_CONNECT_BIT error "
1941 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001942 }
1943 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1944 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001945 RTC_LOG(WARNING)
1946 << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1947 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001948 }
1949 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1950 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001951 RTC_LOG(WARNING)
1952 << "PhysicalSocketServer got FD_CLOSE_BIT error "
1953 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001954 }
1955 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001956 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001957 int errcode = 0;
1958 if (wsaEvents.lNetworkEvents & FD_READ)
1959 ff |= DE_READ;
1960 if (wsaEvents.lNetworkEvents & FD_WRITE)
1961 ff |= DE_WRITE;
1962 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1963 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1964 ff |= DE_CONNECT;
1965 } else {
1966 ff |= DE_CLOSE;
1967 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1968 }
1969 }
1970 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1971 ff |= DE_ACCEPT;
1972 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1973 ff |= DE_CLOSE;
1974 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1975 }
1976 if (ff != 0) {
1977 disp->OnPreEvent(ff);
1978 disp->OnEvent(ff, errcode);
1979 }
1980 }
1981 }
jbauchde4db112017-05-31 13:09:18 -07001982
1983 processing_dispatchers_ = false;
1984 // Process deferred dispatchers that have been added/removed while the
1985 // events were handled above.
1986 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001987 }
1988
1989 // Reset the network event until new activity occurs
1990 WSAResetEvent(socket_ev_);
1991 }
1992
1993 // Break?
1994 if (!fWait_)
1995 break;
1996 cmsElapsed = TimeSince(msStart);
1997 if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
1998 break;
1999 }
2000 }
2001
2002 // Done
2003 return true;
2004}
honghaizcec0a082016-01-15 14:49:09 -08002005#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00002006
2007} // namespace rtc