blob: 422171d4d87d3760317aabbb1a93dbdc4ac8a7c9 [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>
22#include <errno.h>
23#include <fcntl.h>
jbauchde4db112017-05-31 13:09:18 -070024#if defined(WEBRTC_USE_EPOLL)
25// "poll" will be used to wait for the signal dispatcher.
26#include <poll.h>
27#endif
Stefan Holmer9131efd2016-05-23 18:19:26 +020028#include <sys/ioctl.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000029#include <sys/time.h>
30#include <sys/select.h>
31#include <unistd.h>
32#include <signal.h>
33#endif
34
35#if defined(WEBRTC_WIN)
36#define WIN32_LEAN_AND_MEAN
37#include <windows.h>
38#include <winsock2.h>
39#include <ws2tcpip.h>
40#undef SetPort
41#endif
42
43#include <algorithm>
44#include <map>
45
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020046#include "rtc_base/arraysize.h"
47#include "rtc_base/basictypes.h"
48#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
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000056#if defined(WEBRTC_POSIX)
57#include <netinet/tcp.h> // for TCP_NODELAY
58#define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h
59typedef void* SockOptArg;
Stefan Holmer9131efd2016-05-23 18:19:26 +020060
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000061#endif // WEBRTC_POSIX
62
Stefan Holmer3ebb3ef2016-05-23 20:26:11 +020063#if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) && !defined(__native_client__)
64
Stefan Holmer9131efd2016-05-23 18:19:26 +020065int64_t GetSocketRecvTimestamp(int socket) {
66 struct timeval tv_ioctl;
67 int ret = ioctl(socket, SIOCGSTAMP, &tv_ioctl);
68 if (ret != 0)
69 return -1;
70 int64_t timestamp =
71 rtc::kNumMicrosecsPerSec * static_cast<int64_t>(tv_ioctl.tv_sec) +
72 static_cast<int64_t>(tv_ioctl.tv_usec);
73 return timestamp;
74}
75
76#else
77
78int64_t GetSocketRecvTimestamp(int socket) {
79 return -1;
80}
81#endif
82
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000083#if defined(WEBRTC_WIN)
84typedef char* SockOptArg;
85#endif
86
jbauchde4db112017-05-31 13:09:18 -070087#if defined(WEBRTC_USE_EPOLL)
88// POLLRDHUP / EPOLLRDHUP are only defined starting with Linux 2.6.17.
89#if !defined(POLLRDHUP)
90#define POLLRDHUP 0x2000
91#endif
92#if !defined(EPOLLRDHUP)
93#define EPOLLRDHUP 0x2000
94#endif
95#endif
96
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000097namespace rtc {
98
danilchapbebf54c2016-04-28 01:32:48 -070099std::unique_ptr<SocketServer> SocketServer::CreateDefault() {
100#if defined(__native_client__)
101 return std::unique_ptr<SocketServer>(new rtc::NullSocketServer);
102#else
103 return std::unique_ptr<SocketServer>(new rtc::PhysicalSocketServer);
104#endif
105}
106
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000107#if defined(WEBRTC_WIN)
108// Standard MTUs, from RFC 1191
Peter Boström0c4e06b2015-10-07 12:23:21 +0200109const uint16_t PACKET_MAXIMUMS[] = {
110 65535, // Theoretical maximum, Hyperchannel
111 32000, // Nothing
112 17914, // 16Mb IBM Token Ring
113 8166, // IEEE 802.4
114 // 4464, // IEEE 802.5 (4Mb max)
115 4352, // FDDI
116 // 2048, // Wideband Network
117 2002, // IEEE 802.5 (4Mb recommended)
118 // 1536, // Expermental Ethernet Networks
119 // 1500, // Ethernet, Point-to-Point (default)
120 1492, // IEEE 802.3
121 1006, // SLIP, ARPANET
122 // 576, // X.25 Networks
123 // 544, // DEC IP Portal
124 // 512, // NETBIOS
125 508, // IEEE 802/Source-Rt Bridge, ARCNET
126 296, // Point-to-Point (low delay)
127 68, // Official minimum
128 0, // End of list marker
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000129};
130
131static const int IP_HEADER_SIZE = 20u;
132static const int IPV6_HEADER_SIZE = 40u;
133static const int ICMP_HEADER_SIZE = 8u;
134static const int ICMP_PING_TIMEOUT_MILLIS = 10000u;
135#endif
136
jbauch095ae152015-12-18 01:39:55 -0800137PhysicalSocket::PhysicalSocket(PhysicalSocketServer* ss, SOCKET s)
jbauch577f5dc2017-05-17 16:32:26 -0700138 : ss_(ss), s_(s), error_(0),
jbauch095ae152015-12-18 01:39:55 -0800139 state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED),
140 resolver_(nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000141#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800142 // EnsureWinsockInit() ensures that winsock is initialized. The default
143 // version of this function doesn't do anything because winsock is
144 // initialized by constructor of a static object. If neccessary libjingle
145 // users can link it with a different version of this function by replacing
146 // win32socketinit.cc. See win32socketinit.cc for more details.
147 EnsureWinsockInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000148#endif
jbauch095ae152015-12-18 01:39:55 -0800149 if (s_ != INVALID_SOCKET) {
jbauch577f5dc2017-05-17 16:32:26 -0700150 SetEnabledEvents(DE_READ | DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000151
jbauch095ae152015-12-18 01:39:55 -0800152 int type = SOCK_STREAM;
153 socklen_t len = sizeof(type);
nissec16fa5e2017-02-07 07:18:43 -0800154 const int res =
155 getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len);
156 RTC_DCHECK_EQ(0, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000157 udp_ = (SOCK_DGRAM == type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000158 }
jbauch095ae152015-12-18 01:39:55 -0800159}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000160
jbauch095ae152015-12-18 01:39:55 -0800161PhysicalSocket::~PhysicalSocket() {
162 Close();
163}
164
165bool PhysicalSocket::Create(int family, int type) {
166 Close();
167 s_ = ::socket(family, type, 0);
168 udp_ = (SOCK_DGRAM == type);
169 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700170 if (udp_) {
171 SetEnabledEvents(DE_READ | DE_WRITE);
172 }
jbauch095ae152015-12-18 01:39:55 -0800173 return s_ != INVALID_SOCKET;
174}
175
176SocketAddress PhysicalSocket::GetLocalAddress() const {
177 sockaddr_storage addr_storage = {0};
178 socklen_t addrlen = sizeof(addr_storage);
179 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
180 int result = ::getsockname(s_, addr, &addrlen);
181 SocketAddress address;
182 if (result >= 0) {
183 SocketAddressFromSockAddrStorage(addr_storage, &address);
184 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100185 RTC_LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
186 << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000187 }
jbauch095ae152015-12-18 01:39:55 -0800188 return address;
189}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000190
jbauch095ae152015-12-18 01:39:55 -0800191SocketAddress PhysicalSocket::GetRemoteAddress() const {
192 sockaddr_storage addr_storage = {0};
193 socklen_t addrlen = sizeof(addr_storage);
194 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
195 int result = ::getpeername(s_, addr, &addrlen);
196 SocketAddress address;
197 if (result >= 0) {
198 SocketAddressFromSockAddrStorage(addr_storage, &address);
199 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100200 RTC_LOG(LS_WARNING)
201 << "GetRemoteAddress: unable to get remote addr, socket=" << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000202 }
jbauch095ae152015-12-18 01:39:55 -0800203 return address;
204}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000205
jbauch095ae152015-12-18 01:39:55 -0800206int PhysicalSocket::Bind(const SocketAddress& bind_addr) {
deadbeefc874d122017-02-13 15:41:59 -0800207 SocketAddress copied_bind_addr = bind_addr;
208 // If a network binder is available, use it to bind a socket to an interface
209 // instead of bind(), since this is more reliable on an OS with a weak host
210 // model.
deadbeef9ffa13f2017-02-21 16:18:00 -0800211 if (ss_->network_binder() && !bind_addr.IsAnyIP()) {
deadbeefc874d122017-02-13 15:41:59 -0800212 NetworkBindingResult result =
213 ss_->network_binder()->BindSocketToNetwork(s_, bind_addr.ipaddr());
214 if (result == NetworkBindingResult::SUCCESS) {
215 // Since the network binder handled binding the socket to the desired
216 // network interface, we don't need to (and shouldn't) include an IP in
217 // the bind() call; bind() just needs to assign a port.
218 copied_bind_addr.SetIP(GetAnyIP(copied_bind_addr.ipaddr().family()));
219 } else if (result == NetworkBindingResult::NOT_IMPLEMENTED) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100220 RTC_LOG(LS_INFO) << "Can't bind socket to network because "
221 "network binding is not implemented for this OS.";
deadbeefc874d122017-02-13 15:41:59 -0800222 } else {
223 if (bind_addr.IsLoopbackIP()) {
224 // If we couldn't bind to a loopback IP (which should only happen in
225 // test scenarios), continue on. This may be expected behavior.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100226 RTC_LOG(LS_VERBOSE) << "Binding socket to loopback address "
227 << bind_addr.ipaddr().ToString()
228 << " failed; result: " << static_cast<int>(result);
deadbeefc874d122017-02-13 15:41:59 -0800229 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100230 RTC_LOG(LS_WARNING) << "Binding socket to network address "
231 << bind_addr.ipaddr().ToString()
232 << " failed; result: " << static_cast<int>(result);
deadbeefc874d122017-02-13 15:41:59 -0800233 // If a network binding was attempted and failed, we should stop here
234 // and not try to use the socket. Otherwise, we may end up sending
235 // packets with an invalid source address.
236 // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=7026
237 return -1;
238 }
239 }
240 }
jbauch095ae152015-12-18 01:39:55 -0800241 sockaddr_storage addr_storage;
deadbeefc874d122017-02-13 15:41:59 -0800242 size_t len = copied_bind_addr.ToSockAddrStorage(&addr_storage);
jbauch095ae152015-12-18 01:39:55 -0800243 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
244 int err = ::bind(s_, addr, static_cast<int>(len));
245 UpdateLastError();
tfarinaa41ab932015-10-30 16:08:48 -0700246#if !defined(NDEBUG)
jbauch095ae152015-12-18 01:39:55 -0800247 if (0 == err) {
248 dbg_addr_ = "Bound @ ";
249 dbg_addr_.append(GetLocalAddress().ToString());
250 }
tfarinaa41ab932015-10-30 16:08:48 -0700251#endif
jbauch095ae152015-12-18 01:39:55 -0800252 return err;
253}
254
255int PhysicalSocket::Connect(const SocketAddress& addr) {
256 // TODO(pthatcher): Implicit creation is required to reconnect...
257 // ...but should we make it more explicit?
258 if (state_ != CS_CLOSED) {
259 SetError(EALREADY);
260 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000261 }
jbauch095ae152015-12-18 01:39:55 -0800262 if (addr.IsUnresolvedIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100263 RTC_LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
jbauch095ae152015-12-18 01:39:55 -0800264 resolver_ = new AsyncResolver();
265 resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult);
266 resolver_->Start(addr);
267 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000268 return 0;
269 }
270
jbauch095ae152015-12-18 01:39:55 -0800271 return DoConnect(addr);
272}
273
274int PhysicalSocket::DoConnect(const SocketAddress& connect_addr) {
275 if ((s_ == INVALID_SOCKET) &&
276 !Create(connect_addr.family(), SOCK_STREAM)) {
277 return SOCKET_ERROR;
278 }
279 sockaddr_storage addr_storage;
280 size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
281 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
282 int err = ::connect(s_, addr, static_cast<int>(len));
283 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700284 uint8_t events = DE_READ | DE_WRITE;
jbauch095ae152015-12-18 01:39:55 -0800285 if (err == 0) {
286 state_ = CS_CONNECTED;
287 } else if (IsBlockingError(GetError())) {
288 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700289 events |= DE_CONNECT;
jbauch095ae152015-12-18 01:39:55 -0800290 } else {
291 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000292 }
293
jbauch577f5dc2017-05-17 16:32:26 -0700294 EnableEvents(events);
jbauch095ae152015-12-18 01:39:55 -0800295 return 0;
296}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000297
jbauch095ae152015-12-18 01:39:55 -0800298int PhysicalSocket::GetError() const {
299 CritScope cs(&crit_);
300 return error_;
301}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000302
jbauch095ae152015-12-18 01:39:55 -0800303void PhysicalSocket::SetError(int error) {
304 CritScope cs(&crit_);
305 error_ = error;
306}
307
308AsyncSocket::ConnState PhysicalSocket::GetState() const {
309 return state_;
310}
311
312int PhysicalSocket::GetOption(Option opt, int* value) {
313 int slevel;
314 int sopt;
315 if (TranslateOption(opt, &slevel, &sopt) == -1)
316 return -1;
317 socklen_t optlen = sizeof(*value);
318 int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
319 if (ret != -1 && opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000320#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800321 *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000322#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000323 }
jbauch095ae152015-12-18 01:39:55 -0800324 return ret;
325}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000326
jbauch095ae152015-12-18 01:39:55 -0800327int PhysicalSocket::SetOption(Option opt, int value) {
328 int slevel;
329 int sopt;
330 if (TranslateOption(opt, &slevel, &sopt) == -1)
331 return -1;
332 if (opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000333#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800334 value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000335#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000336 }
jbauch095ae152015-12-18 01:39:55 -0800337 return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
338}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000339
jbauch095ae152015-12-18 01:39:55 -0800340int PhysicalSocket::Send(const void* pv, size_t cb) {
jbauchf2a2bf42016-02-03 16:45:32 -0800341 int sent = DoSend(s_, reinterpret_cast<const char *>(pv),
342 static_cast<int>(cb),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000343#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800344 // Suppress SIGPIPE. Without this, attempting to send on a socket whose
345 // other end is closed will result in a SIGPIPE signal being raised to
346 // our process, which by default will terminate the process, which we
347 // don't want. By specifying this flag, we'll just get the error EPIPE
348 // instead and can handle the error gracefully.
349 MSG_NOSIGNAL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000350#else
jbauch095ae152015-12-18 01:39:55 -0800351 0
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000352#endif
jbauch095ae152015-12-18 01:39:55 -0800353 );
354 UpdateLastError();
355 MaybeRemapSendError();
356 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800357 RTC_DCHECK(sent <= static_cast<int>(cb));
jbauchf2a2bf42016-02-03 16:45:32 -0800358 if ((sent > 0 && sent < static_cast<int>(cb)) ||
359 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700360 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000361 }
jbauch095ae152015-12-18 01:39:55 -0800362 return sent;
363}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000364
jbauch095ae152015-12-18 01:39:55 -0800365int PhysicalSocket::SendTo(const void* buffer,
366 size_t length,
367 const SocketAddress& addr) {
368 sockaddr_storage saddr;
369 size_t len = addr.ToSockAddrStorage(&saddr);
jbauchf2a2bf42016-02-03 16:45:32 -0800370 int sent = DoSendTo(
jbauch095ae152015-12-18 01:39:55 -0800371 s_, static_cast<const char *>(buffer), static_cast<int>(length),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000372#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800373 // Suppress SIGPIPE. See above for explanation.
374 MSG_NOSIGNAL,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000375#else
jbauch095ae152015-12-18 01:39:55 -0800376 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000377#endif
jbauch095ae152015-12-18 01:39:55 -0800378 reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
379 UpdateLastError();
380 MaybeRemapSendError();
381 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800382 RTC_DCHECK(sent <= static_cast<int>(length));
jbauchf2a2bf42016-02-03 16:45:32 -0800383 if ((sent > 0 && sent < static_cast<int>(length)) ||
384 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700385 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000386 }
jbauch095ae152015-12-18 01:39:55 -0800387 return sent;
388}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000389
Stefan Holmer9131efd2016-05-23 18:19:26 +0200390int PhysicalSocket::Recv(void* buffer, size_t length, int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800391 int received = ::recv(s_, static_cast<char*>(buffer),
392 static_cast<int>(length), 0);
393 if ((received == 0) && (length != 0)) {
394 // Note: on graceful shutdown, recv can return 0. In this case, we
395 // pretend it is blocking, and then signal close, so that simplifying
396 // assumptions can be made about Recv.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100397 RTC_LOG(LS_WARNING) << "EOF from socket; deferring close event";
jbauch095ae152015-12-18 01:39:55 -0800398 // Must turn this back on so that the select() loop will notice the close
399 // event.
jbauch577f5dc2017-05-17 16:32:26 -0700400 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800401 SetError(EWOULDBLOCK);
402 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000403 }
Stefan Holmer9131efd2016-05-23 18:19:26 +0200404 if (timestamp) {
405 *timestamp = GetSocketRecvTimestamp(s_);
406 }
jbauch095ae152015-12-18 01:39:55 -0800407 UpdateLastError();
408 int error = GetError();
409 bool success = (received >= 0) || IsBlockingError(error);
410 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700411 EnableEvents(DE_READ);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000412 }
jbauch095ae152015-12-18 01:39:55 -0800413 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100414 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000415 }
jbauch095ae152015-12-18 01:39:55 -0800416 return received;
417}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000418
jbauch095ae152015-12-18 01:39:55 -0800419int PhysicalSocket::RecvFrom(void* buffer,
420 size_t length,
Stefan Holmer9131efd2016-05-23 18:19:26 +0200421 SocketAddress* out_addr,
422 int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800423 sockaddr_storage addr_storage;
424 socklen_t addr_len = sizeof(addr_storage);
425 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
426 int received = ::recvfrom(s_, static_cast<char*>(buffer),
427 static_cast<int>(length), 0, addr, &addr_len);
Stefan Holmer9131efd2016-05-23 18:19:26 +0200428 if (timestamp) {
429 *timestamp = GetSocketRecvTimestamp(s_);
430 }
jbauch095ae152015-12-18 01:39:55 -0800431 UpdateLastError();
432 if ((received >= 0) && (out_addr != nullptr))
433 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
434 int error = GetError();
435 bool success = (received >= 0) || IsBlockingError(error);
436 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700437 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800438 }
439 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100440 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
jbauch095ae152015-12-18 01:39:55 -0800441 }
442 return received;
443}
444
445int PhysicalSocket::Listen(int backlog) {
446 int err = ::listen(s_, backlog);
447 UpdateLastError();
448 if (err == 0) {
449 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700450 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800451#if !defined(NDEBUG)
452 dbg_addr_ = "Listening @ ";
453 dbg_addr_.append(GetLocalAddress().ToString());
454#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000455 }
jbauch095ae152015-12-18 01:39:55 -0800456 return err;
457}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000458
jbauch095ae152015-12-18 01:39:55 -0800459AsyncSocket* PhysicalSocket::Accept(SocketAddress* out_addr) {
460 // Always re-subscribe DE_ACCEPT to make sure new incoming connections will
461 // trigger an event even if DoAccept returns an error here.
jbauch577f5dc2017-05-17 16:32:26 -0700462 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800463 sockaddr_storage addr_storage;
464 socklen_t addr_len = sizeof(addr_storage);
465 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
466 SOCKET s = DoAccept(s_, addr, &addr_len);
467 UpdateLastError();
468 if (s == INVALID_SOCKET)
469 return nullptr;
470 if (out_addr != nullptr)
471 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
472 return ss_->WrapSocket(s);
473}
474
475int PhysicalSocket::Close() {
476 if (s_ == INVALID_SOCKET)
477 return 0;
478 int err = ::closesocket(s_);
479 UpdateLastError();
480 s_ = INVALID_SOCKET;
481 state_ = CS_CLOSED;
jbauch577f5dc2017-05-17 16:32:26 -0700482 SetEnabledEvents(0);
jbauch095ae152015-12-18 01:39:55 -0800483 if (resolver_) {
484 resolver_->Destroy(false);
485 resolver_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000486 }
jbauch095ae152015-12-18 01:39:55 -0800487 return err;
488}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000489
jbauch095ae152015-12-18 01:39:55 -0800490SOCKET PhysicalSocket::DoAccept(SOCKET socket,
491 sockaddr* addr,
492 socklen_t* addrlen) {
493 return ::accept(socket, addr, addrlen);
494}
495
jbauchf2a2bf42016-02-03 16:45:32 -0800496int PhysicalSocket::DoSend(SOCKET socket, const char* buf, int len, int flags) {
497 return ::send(socket, buf, len, flags);
498}
499
500int PhysicalSocket::DoSendTo(SOCKET socket,
501 const char* buf,
502 int len,
503 int flags,
504 const struct sockaddr* dest_addr,
505 socklen_t addrlen) {
506 return ::sendto(socket, buf, len, flags, dest_addr, addrlen);
507}
508
jbauch095ae152015-12-18 01:39:55 -0800509void PhysicalSocket::OnResolveResult(AsyncResolverInterface* resolver) {
510 if (resolver != resolver_) {
511 return;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000512 }
513
jbauch095ae152015-12-18 01:39:55 -0800514 int error = resolver_->GetError();
515 if (error == 0) {
516 error = DoConnect(resolver_->address());
517 } else {
518 Close();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000519 }
520
jbauch095ae152015-12-18 01:39:55 -0800521 if (error) {
522 SetError(error);
523 SignalCloseEvent(this, error);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000524 }
jbauch095ae152015-12-18 01:39:55 -0800525}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000526
jbauch095ae152015-12-18 01:39:55 -0800527void PhysicalSocket::UpdateLastError() {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100528 SetError(RTC_LAST_SYSTEM_ERROR);
jbauch095ae152015-12-18 01:39:55 -0800529}
530
531void PhysicalSocket::MaybeRemapSendError() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000532#if defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800533 // https://developer.apple.com/library/mac/documentation/Darwin/
534 // Reference/ManPages/man2/sendto.2.html
535 // ENOBUFS - The output queue for a network interface is full.
536 // This generally indicates that the interface has stopped sending,
537 // but may be caused by transient congestion.
538 if (GetError() == ENOBUFS) {
539 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000540 }
jbauch095ae152015-12-18 01:39:55 -0800541#endif
542}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000543
jbauch577f5dc2017-05-17 16:32:26 -0700544void PhysicalSocket::SetEnabledEvents(uint8_t events) {
545 enabled_events_ = events;
546}
547
548void PhysicalSocket::EnableEvents(uint8_t events) {
549 enabled_events_ |= events;
550}
551
552void PhysicalSocket::DisableEvents(uint8_t events) {
553 enabled_events_ &= ~events;
554}
555
jbauch095ae152015-12-18 01:39:55 -0800556int PhysicalSocket::TranslateOption(Option opt, int* slevel, int* sopt) {
557 switch (opt) {
558 case OPT_DONTFRAGMENT:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000559#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800560 *slevel = IPPROTO_IP;
561 *sopt = IP_DONTFRAGMENT;
562 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000563#elif defined(WEBRTC_MAC) || defined(BSD) || defined(__native_client__)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100564 RTC_LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
jbauch095ae152015-12-18 01:39:55 -0800565 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000566#elif defined(WEBRTC_POSIX)
jbauch095ae152015-12-18 01:39:55 -0800567 *slevel = IPPROTO_IP;
568 *sopt = IP_MTU_DISCOVER;
569 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000570#endif
jbauch095ae152015-12-18 01:39:55 -0800571 case OPT_RCVBUF:
572 *slevel = SOL_SOCKET;
573 *sopt = SO_RCVBUF;
574 break;
575 case OPT_SNDBUF:
576 *slevel = SOL_SOCKET;
577 *sopt = SO_SNDBUF;
578 break;
579 case OPT_NODELAY:
580 *slevel = IPPROTO_TCP;
581 *sopt = TCP_NODELAY;
582 break;
583 case OPT_DSCP:
Mirko Bonadei675513b2017-11-09 11:09:25 +0100584 RTC_LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
jbauch095ae152015-12-18 01:39:55 -0800585 return -1;
586 case OPT_RTP_SENDTIME_EXTN_ID:
587 return -1; // No logging is necessary as this not a OS socket option.
588 default:
nissec80e7412017-01-11 05:56:46 -0800589 RTC_NOTREACHED();
jbauch095ae152015-12-18 01:39:55 -0800590 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000591 }
jbauch095ae152015-12-18 01:39:55 -0800592 return 0;
593}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000594
jbauch4331fcd2016-01-06 22:20:28 -0800595SocketDispatcher::SocketDispatcher(PhysicalSocketServer *ss)
596#if defined(WEBRTC_WIN)
597 : PhysicalSocket(ss), id_(0), signal_close_(false)
598#else
599 : PhysicalSocket(ss)
600#endif
601{
602}
603
604SocketDispatcher::SocketDispatcher(SOCKET s, PhysicalSocketServer *ss)
605#if defined(WEBRTC_WIN)
606 : PhysicalSocket(ss, s), id_(0), signal_close_(false)
607#else
608 : PhysicalSocket(ss, s)
609#endif
610{
611}
612
613SocketDispatcher::~SocketDispatcher() {
614 Close();
615}
616
617bool SocketDispatcher::Initialize() {
nisseede5da42017-01-12 05:15:36 -0800618 RTC_DCHECK(s_ != INVALID_SOCKET);
jbauch4331fcd2016-01-06 22:20:28 -0800619 // Must be a non-blocking
620#if defined(WEBRTC_WIN)
621 u_long argp = 1;
622 ioctlsocket(s_, FIONBIO, &argp);
623#elif defined(WEBRTC_POSIX)
624 fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
625#endif
deadbeefeae45642017-05-26 16:27:09 -0700626#if defined(WEBRTC_IOS)
627 // iOS may kill sockets when the app is moved to the background
628 // (specifically, if the app doesn't use the "voip" UIBackgroundMode). When
629 // we attempt to write to such a socket, SIGPIPE will be raised, which by
630 // default will terminate the process, which we don't want. By specifying
631 // this socket option, SIGPIPE will be disabled for the socket.
632 int value = 1;
633 ::setsockopt(s_, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value));
634#endif
jbauch4331fcd2016-01-06 22:20:28 -0800635 ss_->Add(this);
636 return true;
637}
638
639bool SocketDispatcher::Create(int type) {
640 return Create(AF_INET, type);
641}
642
643bool SocketDispatcher::Create(int family, int type) {
644 // Change the socket to be non-blocking.
645 if (!PhysicalSocket::Create(family, type))
646 return false;
647
648 if (!Initialize())
649 return false;
650
651#if defined(WEBRTC_WIN)
652 do { id_ = ++next_id_; } while (id_ == 0);
653#endif
654 return true;
655}
656
657#if defined(WEBRTC_WIN)
658
659WSAEVENT SocketDispatcher::GetWSAEvent() {
660 return WSA_INVALID_EVENT;
661}
662
663SOCKET SocketDispatcher::GetSocket() {
664 return s_;
665}
666
667bool SocketDispatcher::CheckSignalClose() {
668 if (!signal_close_)
669 return false;
670
671 char ch;
672 if (recv(s_, &ch, 1, MSG_PEEK) > 0)
673 return false;
674
675 state_ = CS_CLOSED;
676 signal_close_ = false;
677 SignalCloseEvent(this, signal_err_);
678 return true;
679}
680
681int SocketDispatcher::next_id_ = 0;
682
683#elif defined(WEBRTC_POSIX)
684
685int SocketDispatcher::GetDescriptor() {
686 return s_;
687}
688
689bool SocketDispatcher::IsDescriptorClosed() {
deadbeeffaedf7f2017-02-09 15:09:22 -0800690 if (udp_) {
691 // The MSG_PEEK trick doesn't work for UDP, since (at least in some
692 // circumstances) it requires reading an entire UDP packet, which would be
693 // bad for performance here. So, just check whether |s_| has been closed,
694 // which should be sufficient.
695 return s_ == INVALID_SOCKET;
696 }
jbauch4331fcd2016-01-06 22:20:28 -0800697 // We don't have a reliable way of distinguishing end-of-stream
698 // from readability. So test on each readable call. Is this
699 // inefficient? Probably.
700 char ch;
701 ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
702 if (res > 0) {
703 // Data available, so not closed.
704 return false;
705 } else if (res == 0) {
706 // EOF, so closed.
707 return true;
708 } else { // error
709 switch (errno) {
710 // Returned if we've already closed s_.
711 case EBADF:
712 // Returned during ungraceful peer shutdown.
713 case ECONNRESET:
714 return true;
deadbeeffaedf7f2017-02-09 15:09:22 -0800715 // The normal blocking error; don't log anything.
716 case EWOULDBLOCK:
717 // Interrupted system call.
718 case EINTR:
719 return false;
jbauch4331fcd2016-01-06 22:20:28 -0800720 default:
721 // Assume that all other errors are just blocking errors, meaning the
722 // connection is still good but we just can't read from it right now.
723 // This should only happen when connecting (and at most once), because
724 // in all other cases this function is only called if the file
725 // descriptor is already known to be in the readable state. However,
726 // it's not necessary a problem if we spuriously interpret a
727 // "connection lost"-type error as a blocking error, because typically
728 // the next recv() will get EOF, so we'll still eventually notice that
729 // the socket is closed.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100730 RTC_LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
jbauch4331fcd2016-01-06 22:20:28 -0800731 return false;
732 }
733 }
734}
735
736#endif // WEBRTC_POSIX
737
738uint32_t SocketDispatcher::GetRequestedEvents() {
jbauch577f5dc2017-05-17 16:32:26 -0700739 return enabled_events();
jbauch4331fcd2016-01-06 22:20:28 -0800740}
741
742void SocketDispatcher::OnPreEvent(uint32_t ff) {
743 if ((ff & DE_CONNECT) != 0)
744 state_ = CS_CONNECTED;
745
746#if defined(WEBRTC_WIN)
747 // We set CS_CLOSED from CheckSignalClose.
748#elif defined(WEBRTC_POSIX)
749 if ((ff & DE_CLOSE) != 0)
750 state_ = CS_CLOSED;
751#endif
752}
753
754#if defined(WEBRTC_WIN)
755
756void SocketDispatcher::OnEvent(uint32_t ff, int err) {
757 int cache_id = id_;
758 // Make sure we deliver connect/accept first. Otherwise, consumers may see
759 // something like a READ followed by a CONNECT, which would be odd.
760 if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
761 if (ff != DE_CONNECT)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100762 RTC_LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
jbauch577f5dc2017-05-17 16:32:26 -0700763 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800764#if !defined(NDEBUG)
765 dbg_addr_ = "Connected @ ";
766 dbg_addr_.append(GetRemoteAddress().ToString());
767#endif
768 SignalConnectEvent(this);
769 }
770 if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700771 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800772 SignalReadEvent(this);
773 }
774 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700775 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800776 SignalReadEvent(this);
777 }
778 if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700779 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800780 SignalWriteEvent(this);
781 }
782 if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
783 signal_close_ = true;
784 signal_err_ = err;
785 }
786}
787
788#elif defined(WEBRTC_POSIX)
789
790void SocketDispatcher::OnEvent(uint32_t ff, int err) {
jbauchde4db112017-05-31 13:09:18 -0700791#if defined(WEBRTC_USE_EPOLL)
792 // Remember currently enabled events so we can combine multiple changes
793 // into one update call later.
794 // The signal handlers might re-enable events disabled here, so we can't
795 // keep a list of events to disable at the end of the method. This list
796 // would not be updated with the events enabled by the signal handlers.
797 StartBatchedEventUpdates();
798#endif
jbauch4331fcd2016-01-06 22:20:28 -0800799 // Make sure we deliver connect/accept first. Otherwise, consumers may see
800 // something like a READ followed by a CONNECT, which would be odd.
801 if ((ff & DE_CONNECT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700802 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800803 SignalConnectEvent(this);
804 }
805 if ((ff & DE_ACCEPT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700806 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800807 SignalReadEvent(this);
808 }
809 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700810 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800811 SignalReadEvent(this);
812 }
813 if ((ff & DE_WRITE) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700814 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800815 SignalWriteEvent(this);
816 }
817 if ((ff & DE_CLOSE) != 0) {
818 // The socket is now dead to us, so stop checking it.
jbauch577f5dc2017-05-17 16:32:26 -0700819 SetEnabledEvents(0);
jbauch4331fcd2016-01-06 22:20:28 -0800820 SignalCloseEvent(this, err);
821 }
jbauchde4db112017-05-31 13:09:18 -0700822#if defined(WEBRTC_USE_EPOLL)
823 FinishBatchedEventUpdates();
824#endif
jbauch4331fcd2016-01-06 22:20:28 -0800825}
826
827#endif // WEBRTC_POSIX
828
jbauchde4db112017-05-31 13:09:18 -0700829#if defined(WEBRTC_USE_EPOLL)
830
831static int GetEpollEvents(uint32_t ff) {
832 int events = 0;
833 if (ff & (DE_READ | DE_ACCEPT)) {
834 events |= EPOLLIN;
835 }
836 if (ff & (DE_WRITE | DE_CONNECT)) {
837 events |= EPOLLOUT;
838 }
839 return events;
840}
841
842void SocketDispatcher::StartBatchedEventUpdates() {
843 RTC_DCHECK_EQ(saved_enabled_events_, -1);
844 saved_enabled_events_ = enabled_events();
845}
846
847void SocketDispatcher::FinishBatchedEventUpdates() {
848 RTC_DCHECK_NE(saved_enabled_events_, -1);
849 uint8_t old_events = static_cast<uint8_t>(saved_enabled_events_);
850 saved_enabled_events_ = -1;
851 MaybeUpdateDispatcher(old_events);
852}
853
854void SocketDispatcher::MaybeUpdateDispatcher(uint8_t old_events) {
855 if (GetEpollEvents(enabled_events()) != GetEpollEvents(old_events) &&
856 saved_enabled_events_ == -1) {
857 ss_->Update(this);
858 }
859}
860
861void SocketDispatcher::SetEnabledEvents(uint8_t events) {
862 uint8_t old_events = enabled_events();
863 PhysicalSocket::SetEnabledEvents(events);
864 MaybeUpdateDispatcher(old_events);
865}
866
867void SocketDispatcher::EnableEvents(uint8_t events) {
868 uint8_t old_events = enabled_events();
869 PhysicalSocket::EnableEvents(events);
870 MaybeUpdateDispatcher(old_events);
871}
872
873void SocketDispatcher::DisableEvents(uint8_t events) {
874 uint8_t old_events = enabled_events();
875 PhysicalSocket::DisableEvents(events);
876 MaybeUpdateDispatcher(old_events);
877}
878
879#endif // WEBRTC_USE_EPOLL
880
jbauch4331fcd2016-01-06 22:20:28 -0800881int SocketDispatcher::Close() {
882 if (s_ == INVALID_SOCKET)
883 return 0;
884
885#if defined(WEBRTC_WIN)
886 id_ = 0;
887 signal_close_ = false;
888#endif
889 ss_->Remove(this);
890 return PhysicalSocket::Close();
891}
892
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000893#if defined(WEBRTC_POSIX)
894class EventDispatcher : public Dispatcher {
895 public:
896 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
897 if (pipe(afd_) < 0)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100898 RTC_LOG(LERROR) << "pipe failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000899 ss_->Add(this);
900 }
901
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000902 ~EventDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000903 ss_->Remove(this);
904 close(afd_[0]);
905 close(afd_[1]);
906 }
907
908 virtual void Signal() {
909 CritScope cs(&crit_);
910 if (!fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200911 const uint8_t b[1] = {0};
nissec16fa5e2017-02-07 07:18:43 -0800912 const ssize_t res = write(afd_[1], b, sizeof(b));
913 RTC_DCHECK_EQ(1, res);
914 fSignaled_ = true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000915 }
916 }
917
Peter Boström0c4e06b2015-10-07 12:23:21 +0200918 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000919
Peter Boström0c4e06b2015-10-07 12:23:21 +0200920 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000921 // It is not possible to perfectly emulate an auto-resetting event with
922 // pipes. This simulates it by resetting before the event is handled.
923
924 CritScope cs(&crit_);
925 if (fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200926 uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
nissec16fa5e2017-02-07 07:18:43 -0800927 const ssize_t res = read(afd_[0], b, sizeof(b));
928 RTC_DCHECK_EQ(1, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000929 fSignaled_ = false;
930 }
931 }
932
nissec80e7412017-01-11 05:56:46 -0800933 void OnEvent(uint32_t ff, int err) override { RTC_NOTREACHED(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000934
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000935 int GetDescriptor() override { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000936
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000937 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000938
939 private:
940 PhysicalSocketServer *ss_;
941 int afd_[2];
942 bool fSignaled_;
943 CriticalSection crit_;
944};
945
946// These two classes use the self-pipe trick to deliver POSIX signals to our
947// select loop. This is the only safe, reliable, cross-platform way to do
948// non-trivial things with a POSIX signal in an event-driven program (until
949// proper pselect() implementations become ubiquitous).
950
951class PosixSignalHandler {
952 public:
953 // POSIX only specifies 32 signals, but in principle the system might have
954 // more and the programmer might choose to use them, so we size our array
955 // for 128.
956 static const int kNumPosixSignals = 128;
957
958 // There is just a single global instance. (Signal handlers do not get any
959 // sort of user-defined void * parameter, so they can't access anything that
960 // isn't global.)
961 static PosixSignalHandler* Instance() {
Andrew MacDonald469c2c02015-05-22 17:50:26 -0700962 RTC_DEFINE_STATIC_LOCAL(PosixSignalHandler, instance, ());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000963 return &instance;
964 }
965
966 // Returns true if the given signal number is set.
967 bool IsSignalSet(int signum) const {
nisseede5da42017-01-12 05:15:36 -0800968 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800969 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000970 return received_signal_[signum];
971 } else {
972 return false;
973 }
974 }
975
976 // Clears the given signal number.
977 void ClearSignal(int signum) {
nisseede5da42017-01-12 05:15:36 -0800978 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800979 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000980 received_signal_[signum] = false;
981 }
982 }
983
984 // Returns the file descriptor to monitor for signal events.
985 int GetDescriptor() const {
986 return afd_[0];
987 }
988
989 // This is called directly from our real signal handler, so it must be
990 // signal-handler-safe. That means it cannot assume anything about the
991 // user-level state of the process, since the handler could be executed at any
992 // time on any thread.
993 void OnPosixSignalReceived(int signum) {
tfarina5237aaf2015-11-10 23:44:30 -0800994 if (signum >= static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000995 // We don't have space in our array for this.
996 return;
997 }
998 // Set a flag saying we've seen this signal.
999 received_signal_[signum] = true;
1000 // Notify application code that we got a signal.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001001 const uint8_t b[1] = {0};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001002 if (-1 == write(afd_[1], b, sizeof(b))) {
1003 // Nothing we can do here. If there's an error somehow then there's
1004 // nothing we can safely do from a signal handler.
1005 // No, we can't even safely log it.
1006 // But, we still have to check the return value here. Otherwise,
1007 // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
1008 return;
1009 }
1010 }
1011
1012 private:
1013 PosixSignalHandler() {
1014 if (pipe(afd_) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001015 RTC_LOG_ERR(LS_ERROR) << "pipe failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001016 return;
1017 }
1018 if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001019 RTC_LOG_ERR(LS_WARNING) << "fcntl #1 failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001020 }
1021 if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001022 RTC_LOG_ERR(LS_WARNING) << "fcntl #2 failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001023 }
1024 memset(const_cast<void *>(static_cast<volatile void *>(received_signal_)),
1025 0,
1026 sizeof(received_signal_));
1027 }
1028
1029 ~PosixSignalHandler() {
1030 int fd1 = afd_[0];
1031 int fd2 = afd_[1];
1032 // We clobber the stored file descriptor numbers here or else in principle
1033 // a signal that happens to be delivered during application termination
1034 // could erroneously write a zero byte to an unrelated file handle in
1035 // OnPosixSignalReceived() if some other file happens to be opened later
1036 // during shutdown and happens to be given the same file descriptor number
1037 // as our pipe had. Unfortunately even with this precaution there is still a
1038 // race where that could occur if said signal happens to be handled
1039 // concurrently with this code and happens to have already read the value of
1040 // afd_[1] from memory before we clobber it, but that's unlikely.
1041 afd_[0] = -1;
1042 afd_[1] = -1;
1043 close(fd1);
1044 close(fd2);
1045 }
1046
1047 int afd_[2];
1048 // These are boolean flags that will be set in our signal handler and read
1049 // and cleared from Wait(). There is a race involved in this, but it is
1050 // benign. The signal handler sets the flag before signaling the pipe, so
1051 // we'll never end up blocking in select() while a flag is still true.
1052 // However, if two of the same signal arrive close to each other then it's
1053 // possible that the second time the handler may set the flag while it's still
1054 // true, meaning that signal will be missed. But the first occurrence of it
1055 // will still be handled, so this isn't a problem.
1056 // Volatile is not necessary here for correctness, but this data _is_ volatile
1057 // so I've marked it as such.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001058 volatile uint8_t received_signal_[kNumPosixSignals];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001059};
1060
1061class PosixSignalDispatcher : public Dispatcher {
1062 public:
1063 PosixSignalDispatcher(PhysicalSocketServer *owner) : owner_(owner) {
1064 owner_->Add(this);
1065 }
1066
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001067 ~PosixSignalDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001068 owner_->Remove(this);
1069 }
1070
Peter Boström0c4e06b2015-10-07 12:23:21 +02001071 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001072
Peter Boström0c4e06b2015-10-07 12:23:21 +02001073 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001074 // Events might get grouped if signals come very fast, so we read out up to
1075 // 16 bytes to make sure we keep the pipe empty.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001076 uint8_t b[16];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001077 ssize_t ret = read(GetDescriptor(), b, sizeof(b));
1078 if (ret < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001079 RTC_LOG_ERR(LS_WARNING) << "Error in read()";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001080 } else if (ret == 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001081 RTC_LOG(LS_WARNING) << "Should have read at least one byte";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001082 }
1083 }
1084
Peter Boström0c4e06b2015-10-07 12:23:21 +02001085 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001086 for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
1087 ++signum) {
1088 if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
1089 PosixSignalHandler::Instance()->ClearSignal(signum);
1090 HandlerMap::iterator i = handlers_.find(signum);
1091 if (i == handlers_.end()) {
1092 // This can happen if a signal is delivered to our process at around
1093 // the same time as we unset our handler for it. It is not an error
1094 // condition, but it's unusual enough to be worth logging.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001095 RTC_LOG(LS_INFO) << "Received signal with no handler: " << signum;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001096 } else {
1097 // Otherwise, execute our handler.
1098 (*i->second)(signum);
1099 }
1100 }
1101 }
1102 }
1103
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001104 int GetDescriptor() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001105 return PosixSignalHandler::Instance()->GetDescriptor();
1106 }
1107
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001108 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001109
1110 void SetHandler(int signum, void (*handler)(int)) {
1111 handlers_[signum] = handler;
1112 }
1113
1114 void ClearHandler(int signum) {
1115 handlers_.erase(signum);
1116 }
1117
1118 bool HasHandlers() {
1119 return !handlers_.empty();
1120 }
1121
1122 private:
1123 typedef std::map<int, void (*)(int)> HandlerMap;
1124
1125 HandlerMap handlers_;
1126 // Our owner.
1127 PhysicalSocketServer *owner_;
1128};
1129
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001130#endif // WEBRTC_POSIX
1131
1132#if defined(WEBRTC_WIN)
Peter Boström0c4e06b2015-10-07 12:23:21 +02001133static uint32_t FlagsToEvents(uint32_t events) {
1134 uint32_t ffFD = FD_CLOSE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001135 if (events & DE_READ)
1136 ffFD |= FD_READ;
1137 if (events & DE_WRITE)
1138 ffFD |= FD_WRITE;
1139 if (events & DE_CONNECT)
1140 ffFD |= FD_CONNECT;
1141 if (events & DE_ACCEPT)
1142 ffFD |= FD_ACCEPT;
1143 return ffFD;
1144}
1145
1146class EventDispatcher : public Dispatcher {
1147 public:
1148 EventDispatcher(PhysicalSocketServer *ss) : ss_(ss) {
1149 hev_ = WSACreateEvent();
1150 if (hev_) {
1151 ss_->Add(this);
1152 }
1153 }
1154
Steve Anton9de3aac2017-10-24 10:08:26 -07001155 ~EventDispatcher() override {
deadbeef37f5ecf2017-02-27 14:06:41 -08001156 if (hev_ != nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001157 ss_->Remove(this);
1158 WSACloseEvent(hev_);
deadbeef37f5ecf2017-02-27 14:06:41 -08001159 hev_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001160 }
1161 }
1162
1163 virtual void Signal() {
deadbeef37f5ecf2017-02-27 14:06:41 -08001164 if (hev_ != nullptr)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001165 WSASetEvent(hev_);
1166 }
1167
Steve Anton9de3aac2017-10-24 10:08:26 -07001168 uint32_t GetRequestedEvents() override { return 0; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001169
Steve Anton9de3aac2017-10-24 10:08:26 -07001170 void OnPreEvent(uint32_t ff) override { WSAResetEvent(hev_); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001171
Steve Anton9de3aac2017-10-24 10:08:26 -07001172 void OnEvent(uint32_t ff, int err) override {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001173
Steve Anton9de3aac2017-10-24 10:08:26 -07001174 WSAEVENT GetWSAEvent() override { return hev_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001175
Steve Anton9de3aac2017-10-24 10:08:26 -07001176 SOCKET GetSocket() override { return INVALID_SOCKET; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001177
Steve Anton9de3aac2017-10-24 10:08:26 -07001178 bool CheckSignalClose() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001179
Steve Anton9de3aac2017-10-24 10:08:26 -07001180 private:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001181 PhysicalSocketServer* ss_;
1182 WSAEVENT hev_;
1183};
honghaizcec0a082016-01-15 14:49:09 -08001184#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001185
1186// Sets the value of a boolean value to false when signaled.
1187class Signaler : public EventDispatcher {
1188 public:
1189 Signaler(PhysicalSocketServer* ss, bool* pf)
1190 : EventDispatcher(ss), pf_(pf) {
1191 }
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001192 ~Signaler() override { }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001193
Peter Boström0c4e06b2015-10-07 12:23:21 +02001194 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001195 if (pf_)
1196 *pf_ = false;
1197 }
1198
1199 private:
1200 bool *pf_;
1201};
1202
1203PhysicalSocketServer::PhysicalSocketServer()
1204 : fWait_(false) {
jbauchde4db112017-05-31 13:09:18 -07001205#if defined(WEBRTC_USE_EPOLL)
1206 // Since Linux 2.6.8, the size argument is ignored, but must be greater than
1207 // zero. Before that the size served as hint to the kernel for the amount of
1208 // space to initially allocate in internal data structures.
1209 epoll_fd_ = epoll_create(FD_SETSIZE);
1210 if (epoll_fd_ == -1) {
1211 // Not an error, will fall back to "select" below.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001212 RTC_LOG_E(LS_WARNING, EN, errno) << "epoll_create";
jbauchde4db112017-05-31 13:09:18 -07001213 epoll_fd_ = INVALID_SOCKET;
1214 }
1215#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001216 signal_wakeup_ = new Signaler(this, &fWait_);
1217#if defined(WEBRTC_WIN)
1218 socket_ev_ = WSACreateEvent();
1219#endif
1220}
1221
1222PhysicalSocketServer::~PhysicalSocketServer() {
1223#if defined(WEBRTC_WIN)
1224 WSACloseEvent(socket_ev_);
1225#endif
1226#if defined(WEBRTC_POSIX)
1227 signal_dispatcher_.reset();
1228#endif
1229 delete signal_wakeup_;
jbauchde4db112017-05-31 13:09:18 -07001230#if defined(WEBRTC_USE_EPOLL)
1231 if (epoll_fd_ != INVALID_SOCKET) {
1232 close(epoll_fd_);
1233 }
1234#endif
nisseede5da42017-01-12 05:15:36 -08001235 RTC_DCHECK(dispatchers_.empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001236}
1237
1238void PhysicalSocketServer::WakeUp() {
1239 signal_wakeup_->Signal();
1240}
1241
1242Socket* PhysicalSocketServer::CreateSocket(int type) {
1243 return CreateSocket(AF_INET, type);
1244}
1245
1246Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
1247 PhysicalSocket* socket = new PhysicalSocket(this);
1248 if (socket->Create(family, type)) {
1249 return socket;
1250 } else {
1251 delete socket;
jbauch095ae152015-12-18 01:39:55 -08001252 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001253 }
1254}
1255
1256AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int type) {
1257 return CreateAsyncSocket(AF_INET, type);
1258}
1259
1260AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
1261 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1262 if (dispatcher->Create(family, type)) {
1263 return dispatcher;
1264 } else {
1265 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001266 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001267 }
1268}
1269
1270AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
1271 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1272 if (dispatcher->Initialize()) {
1273 return dispatcher;
1274 } else {
1275 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001276 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001277 }
1278}
1279
1280void PhysicalSocketServer::Add(Dispatcher *pdispatcher) {
1281 CritScope cs(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001282 if (processing_dispatchers_) {
1283 // A dispatcher is being added while a "Wait" call is processing the
1284 // list of socket events.
1285 // Defer adding to "dispatchers_" set until processing is done to avoid
1286 // invalidating the iterator in "Wait".
1287 pending_remove_dispatchers_.erase(pdispatcher);
1288 pending_add_dispatchers_.insert(pdispatcher);
1289 } else {
1290 dispatchers_.insert(pdispatcher);
1291 }
1292#if defined(WEBRTC_USE_EPOLL)
1293 if (epoll_fd_ != INVALID_SOCKET) {
1294 AddEpoll(pdispatcher);
1295 }
1296#endif // WEBRTC_USE_EPOLL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001297}
1298
1299void PhysicalSocketServer::Remove(Dispatcher *pdispatcher) {
1300 CritScope cs(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001301 if (processing_dispatchers_) {
1302 // A dispatcher is being removed while a "Wait" call is processing the
1303 // list of socket events.
1304 // Defer removal from "dispatchers_" set until processing is done to avoid
1305 // invalidating the iterator in "Wait".
1306 if (!pending_add_dispatchers_.erase(pdispatcher) &&
1307 dispatchers_.find(pdispatcher) == dispatchers_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001308 RTC_LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
1309 << "dispatcher, potentially from a duplicate call to "
1310 << "Add.";
jbauchde4db112017-05-31 13:09:18 -07001311 return;
1312 }
1313
1314 pending_remove_dispatchers_.insert(pdispatcher);
1315 } else if (!dispatchers_.erase(pdispatcher)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001316 RTC_LOG(LS_WARNING)
1317 << "PhysicalSocketServer asked to remove a unknown "
1318 << "dispatcher, potentially from a duplicate call to Add.";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001319 return;
1320 }
jbauchde4db112017-05-31 13:09:18 -07001321#if defined(WEBRTC_USE_EPOLL)
1322 if (epoll_fd_ != INVALID_SOCKET) {
1323 RemoveEpoll(pdispatcher);
1324 }
1325#endif // WEBRTC_USE_EPOLL
1326}
1327
1328void PhysicalSocketServer::Update(Dispatcher* pdispatcher) {
1329#if defined(WEBRTC_USE_EPOLL)
1330 if (epoll_fd_ == INVALID_SOCKET) {
1331 return;
1332 }
1333
1334 CritScope cs(&crit_);
1335 if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1336 return;
1337 }
1338
1339 UpdateEpoll(pdispatcher);
1340#endif
1341}
1342
1343void PhysicalSocketServer::AddRemovePendingDispatchers() {
1344 if (!pending_add_dispatchers_.empty()) {
1345 for (Dispatcher* pdispatcher : pending_add_dispatchers_) {
1346 dispatchers_.insert(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001347 }
jbauchde4db112017-05-31 13:09:18 -07001348 pending_add_dispatchers_.clear();
1349 }
1350
1351 if (!pending_remove_dispatchers_.empty()) {
1352 for (Dispatcher* pdispatcher : pending_remove_dispatchers_) {
1353 dispatchers_.erase(pdispatcher);
1354 }
1355 pending_remove_dispatchers_.clear();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001356 }
1357}
1358
1359#if defined(WEBRTC_POSIX)
jbauchde4db112017-05-31 13:09:18 -07001360
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001361bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
jbauchde4db112017-05-31 13:09:18 -07001362#if defined(WEBRTC_USE_EPOLL)
1363 // We don't keep a dedicated "epoll" descriptor containing only the non-IO
1364 // (i.e. signaling) dispatcher, so "poll" will be used instead of the default
1365 // "select" to support sockets larger than FD_SETSIZE.
1366 if (!process_io) {
1367 return WaitPoll(cmsWait, signal_wakeup_);
1368 } else if (epoll_fd_ != INVALID_SOCKET) {
1369 return WaitEpoll(cmsWait);
1370 }
1371#endif
1372 return WaitSelect(cmsWait, process_io);
1373}
1374
1375static void ProcessEvents(Dispatcher* dispatcher,
1376 bool readable,
1377 bool writable,
1378 bool check_error) {
1379 int errcode = 0;
1380 // TODO(pthatcher): Should we set errcode if getsockopt fails?
1381 if (check_error) {
1382 socklen_t len = sizeof(errcode);
1383 ::getsockopt(dispatcher->GetDescriptor(), SOL_SOCKET, SO_ERROR, &errcode,
1384 &len);
1385 }
1386
1387 uint32_t ff = 0;
1388
1389 // Check readable descriptors. If we're waiting on an accept, signal
1390 // that. Otherwise we're waiting for data, check to see if we're
1391 // readable or really closed.
1392 // TODO(pthatcher): Only peek at TCP descriptors.
1393 if (readable) {
1394 if (dispatcher->GetRequestedEvents() & DE_ACCEPT) {
1395 ff |= DE_ACCEPT;
1396 } else if (errcode || dispatcher->IsDescriptorClosed()) {
1397 ff |= DE_CLOSE;
1398 } else {
1399 ff |= DE_READ;
1400 }
1401 }
1402
1403 // Check writable descriptors. If we're waiting on a connect, detect
1404 // success versus failure by the reaped error code.
1405 if (writable) {
1406 if (dispatcher->GetRequestedEvents() & DE_CONNECT) {
1407 if (!errcode) {
1408 ff |= DE_CONNECT;
1409 } else {
1410 ff |= DE_CLOSE;
1411 }
1412 } else {
1413 ff |= DE_WRITE;
1414 }
1415 }
1416
1417 // Tell the descriptor about the event.
1418 if (ff != 0) {
1419 dispatcher->OnPreEvent(ff);
1420 dispatcher->OnEvent(ff, errcode);
1421 }
1422}
1423
1424bool PhysicalSocketServer::WaitSelect(int cmsWait, bool process_io) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001425 // Calculate timing information
1426
deadbeef37f5ecf2017-02-27 14:06:41 -08001427 struct timeval* ptvWait = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001428 struct timeval tvWait;
1429 struct timeval tvStop;
1430 if (cmsWait != kForever) {
1431 // Calculate wait timeval
1432 tvWait.tv_sec = cmsWait / 1000;
1433 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1434 ptvWait = &tvWait;
1435
1436 // Calculate when to return in a timeval
deadbeef37f5ecf2017-02-27 14:06:41 -08001437 gettimeofday(&tvStop, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001438 tvStop.tv_sec += tvWait.tv_sec;
1439 tvStop.tv_usec += tvWait.tv_usec;
1440 if (tvStop.tv_usec >= 1000000) {
1441 tvStop.tv_usec -= 1000000;
1442 tvStop.tv_sec += 1;
1443 }
1444 }
1445
1446 // Zero all fd_sets. Don't need to do this inside the loop since
1447 // select() zeros the descriptors not signaled
1448
1449 fd_set fdsRead;
1450 FD_ZERO(&fdsRead);
1451 fd_set fdsWrite;
1452 FD_ZERO(&fdsWrite);
pbos@webrtc.org27e58982014-10-07 17:56:53 +00001453 // Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1454 // inline assembly in FD_ZERO.
1455 // http://crbug.com/344505
1456#ifdef MEMORY_SANITIZER
1457 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1458 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1459#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001460
1461 fWait_ = true;
1462
1463 while (fWait_) {
1464 int fdmax = -1;
1465 {
1466 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001467 // TODO(jbauch): Support re-entrant waiting.
1468 RTC_DCHECK(!processing_dispatchers_);
1469 for (Dispatcher* pdispatcher : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001470 // Query dispatchers for read and write wait state
nisseede5da42017-01-12 05:15:36 -08001471 RTC_DCHECK(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001472 if (!process_io && (pdispatcher != signal_wakeup_))
1473 continue;
1474 int fd = pdispatcher->GetDescriptor();
jbauchde4db112017-05-31 13:09:18 -07001475 // "select"ing a file descriptor that is equal to or larger than
1476 // FD_SETSIZE will result in undefined behavior.
1477 RTC_DCHECK_LT(fd, FD_SETSIZE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001478 if (fd > fdmax)
1479 fdmax = fd;
1480
Peter Boström0c4e06b2015-10-07 12:23:21 +02001481 uint32_t ff = pdispatcher->GetRequestedEvents();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001482 if (ff & (DE_READ | DE_ACCEPT))
1483 FD_SET(fd, &fdsRead);
1484 if (ff & (DE_WRITE | DE_CONNECT))
1485 FD_SET(fd, &fdsWrite);
1486 }
1487 }
1488
1489 // Wait then call handlers as appropriate
1490 // < 0 means error
1491 // 0 means timeout
1492 // > 0 means count of descriptors ready
deadbeef37f5ecf2017-02-27 14:06:41 -08001493 int n = select(fdmax + 1, &fdsRead, &fdsWrite, nullptr, ptvWait);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001494
1495 // If error, return error.
1496 if (n < 0) {
1497 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001498 RTC_LOG_E(LS_ERROR, EN, errno) << "select";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001499 return false;
1500 }
1501 // Else ignore the error and keep going. If this EINTR was for one of the
1502 // signals managed by this PhysicalSocketServer, the
1503 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1504 // iteration.
1505 } else if (n == 0) {
1506 // If timeout, return success
1507 return true;
1508 } else {
1509 // We have signaled descriptors
1510 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001511 processing_dispatchers_ = true;
1512 for (Dispatcher* pdispatcher : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001513 int fd = pdispatcher->GetDescriptor();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001514
jbauchde4db112017-05-31 13:09:18 -07001515 bool readable = FD_ISSET(fd, &fdsRead);
1516 if (readable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001517 FD_CLR(fd, &fdsRead);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001518 }
1519
jbauchde4db112017-05-31 13:09:18 -07001520 bool writable = FD_ISSET(fd, &fdsWrite);
1521 if (writable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001522 FD_CLR(fd, &fdsWrite);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001523 }
1524
jbauchde4db112017-05-31 13:09:18 -07001525 // The error code can be signaled through reads or writes.
1526 ProcessEvents(pdispatcher, readable, writable, readable || writable);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001527 }
jbauchde4db112017-05-31 13:09:18 -07001528
1529 processing_dispatchers_ = false;
1530 // Process deferred dispatchers that have been added/removed while the
1531 // events were handled above.
1532 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001533 }
1534
1535 // Recalc the time remaining to wait. Doing it here means it doesn't get
1536 // calced twice the first time through the loop
1537 if (ptvWait) {
1538 ptvWait->tv_sec = 0;
1539 ptvWait->tv_usec = 0;
1540 struct timeval tvT;
deadbeef37f5ecf2017-02-27 14:06:41 -08001541 gettimeofday(&tvT, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001542 if ((tvStop.tv_sec > tvT.tv_sec)
1543 || ((tvStop.tv_sec == tvT.tv_sec)
1544 && (tvStop.tv_usec > tvT.tv_usec))) {
1545 ptvWait->tv_sec = tvStop.tv_sec - tvT.tv_sec;
1546 ptvWait->tv_usec = tvStop.tv_usec - tvT.tv_usec;
1547 if (ptvWait->tv_usec < 0) {
nisseede5da42017-01-12 05:15:36 -08001548 RTC_DCHECK(ptvWait->tv_sec > 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001549 ptvWait->tv_usec += 1000000;
1550 ptvWait->tv_sec -= 1;
1551 }
1552 }
1553 }
1554 }
1555
1556 return true;
1557}
1558
jbauchde4db112017-05-31 13:09:18 -07001559#if defined(WEBRTC_USE_EPOLL)
1560
1561// Initial number of events to process with one call to "epoll_wait".
1562static const size_t kInitialEpollEvents = 128;
1563
1564// Maximum number of events to process with one call to "epoll_wait".
1565static const size_t kMaxEpollEvents = 8192;
1566
1567void PhysicalSocketServer::AddEpoll(Dispatcher* pdispatcher) {
1568 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1569 int fd = pdispatcher->GetDescriptor();
1570 RTC_DCHECK(fd != INVALID_SOCKET);
1571 if (fd == INVALID_SOCKET) {
1572 return;
1573 }
1574
1575 struct epoll_event event = {0};
1576 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
1577 event.data.ptr = pdispatcher;
1578 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &event);
1579 RTC_DCHECK_EQ(err, 0);
1580 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001581 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_ADD";
jbauchde4db112017-05-31 13:09:18 -07001582 }
1583}
1584
1585void PhysicalSocketServer::RemoveEpoll(Dispatcher* pdispatcher) {
1586 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1587 int fd = pdispatcher->GetDescriptor();
1588 RTC_DCHECK(fd != INVALID_SOCKET);
1589 if (fd == INVALID_SOCKET) {
1590 return;
1591 }
1592
1593 struct epoll_event event = {0};
1594 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &event);
1595 RTC_DCHECK(err == 0 || errno == ENOENT);
1596 if (err == -1) {
1597 if (errno == ENOENT) {
1598 // Socket has already been closed.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001599 RTC_LOG_E(LS_VERBOSE, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001600 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001601 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001602 }
1603 }
1604}
1605
1606void PhysicalSocketServer::UpdateEpoll(Dispatcher* pdispatcher) {
1607 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1608 int fd = pdispatcher->GetDescriptor();
1609 RTC_DCHECK(fd != INVALID_SOCKET);
1610 if (fd == INVALID_SOCKET) {
1611 return;
1612 }
1613
1614 struct epoll_event event = {0};
1615 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
1616 event.data.ptr = pdispatcher;
1617 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &event);
1618 RTC_DCHECK_EQ(err, 0);
1619 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001620 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_MOD";
jbauchde4db112017-05-31 13:09:18 -07001621 }
1622}
1623
1624bool PhysicalSocketServer::WaitEpoll(int cmsWait) {
1625 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1626 int64_t tvWait = -1;
1627 int64_t tvStop = -1;
1628 if (cmsWait != kForever) {
1629 tvWait = cmsWait;
1630 tvStop = TimeAfter(cmsWait);
1631 }
1632
1633 if (epoll_events_.empty()) {
1634 // The initial space to receive events is created only if epoll is used.
1635 epoll_events_.resize(kInitialEpollEvents);
1636 }
1637
1638 fWait_ = true;
1639
1640 while (fWait_) {
1641 // Wait then call handlers as appropriate
1642 // < 0 means error
1643 // 0 means timeout
1644 // > 0 means count of descriptors ready
1645 int n = epoll_wait(epoll_fd_, &epoll_events_[0],
1646 static_cast<int>(epoll_events_.size()),
1647 static_cast<int>(tvWait));
1648 if (n < 0) {
1649 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001650 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll";
jbauchde4db112017-05-31 13:09:18 -07001651 return false;
1652 }
1653 // Else ignore the error and keep going. If this EINTR was for one of the
1654 // signals managed by this PhysicalSocketServer, the
1655 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1656 // iteration.
1657 } else if (n == 0) {
1658 // If timeout, return success
1659 return true;
1660 } else {
1661 // We have signaled descriptors
1662 CritScope cr(&crit_);
1663 for (int i = 0; i < n; ++i) {
1664 const epoll_event& event = epoll_events_[i];
1665 Dispatcher* pdispatcher = static_cast<Dispatcher*>(event.data.ptr);
1666 if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1667 // The dispatcher for this socket no longer exists.
1668 continue;
1669 }
1670
1671 bool readable = (event.events & (EPOLLIN | EPOLLPRI));
1672 bool writable = (event.events & EPOLLOUT);
1673 bool check_error = (event.events & (EPOLLRDHUP | EPOLLERR | EPOLLHUP));
1674
1675 ProcessEvents(pdispatcher, readable, writable, check_error);
1676 }
1677 }
1678
1679 if (static_cast<size_t>(n) == epoll_events_.size() &&
1680 epoll_events_.size() < kMaxEpollEvents) {
1681 // We used the complete space to receive events, increase size for future
1682 // iterations.
1683 epoll_events_.resize(std::max(epoll_events_.size() * 2, kMaxEpollEvents));
1684 }
1685
1686 if (cmsWait != kForever) {
1687 tvWait = TimeDiff(tvStop, TimeMillis());
1688 if (tvWait < 0) {
1689 // Return success on timeout.
1690 return true;
1691 }
1692 }
1693 }
1694
1695 return true;
1696}
1697
1698bool PhysicalSocketServer::WaitPoll(int cmsWait, Dispatcher* dispatcher) {
1699 RTC_DCHECK(dispatcher);
1700 int64_t tvWait = -1;
1701 int64_t tvStop = -1;
1702 if (cmsWait != kForever) {
1703 tvWait = cmsWait;
1704 tvStop = TimeAfter(cmsWait);
1705 }
1706
1707 fWait_ = true;
1708
1709 struct pollfd fds = {0};
1710 int fd = dispatcher->GetDescriptor();
1711 fds.fd = fd;
1712
1713 while (fWait_) {
1714 uint32_t ff = dispatcher->GetRequestedEvents();
1715 fds.events = 0;
1716 if (ff & (DE_READ | DE_ACCEPT)) {
1717 fds.events |= POLLIN;
1718 }
1719 if (ff & (DE_WRITE | DE_CONNECT)) {
1720 fds.events |= POLLOUT;
1721 }
1722 fds.revents = 0;
1723
1724 // Wait then call handlers as appropriate
1725 // < 0 means error
1726 // 0 means timeout
1727 // > 0 means count of descriptors ready
1728 int n = poll(&fds, 1, static_cast<int>(tvWait));
1729 if (n < 0) {
1730 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001731 RTC_LOG_E(LS_ERROR, EN, errno) << "poll";
jbauchde4db112017-05-31 13:09:18 -07001732 return false;
1733 }
1734 // Else ignore the error and keep going. If this EINTR was for one of the
1735 // signals managed by this PhysicalSocketServer, the
1736 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1737 // iteration.
1738 } else if (n == 0) {
1739 // If timeout, return success
1740 return true;
1741 } else {
1742 // We have signaled descriptors (should only be the passed dispatcher).
1743 RTC_DCHECK_EQ(n, 1);
1744 RTC_DCHECK_EQ(fds.fd, fd);
1745
1746 bool readable = (fds.revents & (POLLIN | POLLPRI));
1747 bool writable = (fds.revents & POLLOUT);
1748 bool check_error = (fds.revents & (POLLRDHUP | POLLERR | POLLHUP));
1749
1750 ProcessEvents(dispatcher, readable, writable, check_error);
1751 }
1752
1753 if (cmsWait != kForever) {
1754 tvWait = TimeDiff(tvStop, TimeMillis());
1755 if (tvWait < 0) {
1756 // Return success on timeout.
1757 return true;
1758 }
1759 }
1760 }
1761
1762 return true;
1763}
1764
1765#endif // WEBRTC_USE_EPOLL
1766
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001767static void GlobalSignalHandler(int signum) {
1768 PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
1769}
1770
1771bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
1772 void (*handler)(int)) {
1773 // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
1774 // otherwise set one.
1775 if (handler == SIG_IGN || handler == SIG_DFL) {
1776 if (!InstallSignal(signum, handler)) {
1777 return false;
1778 }
1779 if (signal_dispatcher_) {
1780 signal_dispatcher_->ClearHandler(signum);
1781 if (!signal_dispatcher_->HasHandlers()) {
1782 signal_dispatcher_.reset();
1783 }
1784 }
1785 } else {
1786 if (!signal_dispatcher_) {
1787 signal_dispatcher_.reset(new PosixSignalDispatcher(this));
1788 }
1789 signal_dispatcher_->SetHandler(signum, handler);
1790 if (!InstallSignal(signum, &GlobalSignalHandler)) {
1791 return false;
1792 }
1793 }
1794 return true;
1795}
1796
1797Dispatcher* PhysicalSocketServer::signal_dispatcher() {
1798 return signal_dispatcher_.get();
1799}
1800
1801bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
1802 struct sigaction act;
1803 // It doesn't really matter what we set this mask to.
1804 if (sigemptyset(&act.sa_mask) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001805 RTC_LOG_ERR(LS_ERROR) << "Couldn't set mask";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001806 return false;
1807 }
1808 act.sa_handler = handler;
1809#if !defined(__native_client__)
1810 // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
1811 // and it's a nuisance. Though some syscalls still return EINTR and there's no
1812 // real standard for which ones. :(
1813 act.sa_flags = SA_RESTART;
1814#else
1815 act.sa_flags = 0;
1816#endif
deadbeef37f5ecf2017-02-27 14:06:41 -08001817 if (sigaction(signum, &act, nullptr) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001818 RTC_LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001819 return false;
1820 }
1821 return true;
1822}
1823#endif // WEBRTC_POSIX
1824
1825#if defined(WEBRTC_WIN)
1826bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
Honghai Zhang82d78622016-05-06 11:29:15 -07001827 int64_t cmsTotal = cmsWait;
1828 int64_t cmsElapsed = 0;
1829 int64_t msStart = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001830
1831 fWait_ = true;
1832 while (fWait_) {
1833 std::vector<WSAEVENT> events;
1834 std::vector<Dispatcher *> event_owners;
1835
1836 events.push_back(socket_ev_);
1837
1838 {
1839 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001840 // TODO(jbauch): Support re-entrant waiting.
1841 RTC_DCHECK(!processing_dispatchers_);
1842
1843 // Calling "CheckSignalClose" might remove a closed dispatcher from the
1844 // set. This must be deferred to prevent invalidating the iterator.
1845 processing_dispatchers_ = true;
1846 for (Dispatcher* disp : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001847 if (!process_io && (disp != signal_wakeup_))
1848 continue;
1849 SOCKET s = disp->GetSocket();
1850 if (disp->CheckSignalClose()) {
1851 // We just signalled close, don't poll this socket
1852 } else if (s != INVALID_SOCKET) {
1853 WSAEventSelect(s,
1854 events[0],
1855 FlagsToEvents(disp->GetRequestedEvents()));
1856 } else {
1857 events.push_back(disp->GetWSAEvent());
1858 event_owners.push_back(disp);
1859 }
1860 }
jbauchde4db112017-05-31 13:09:18 -07001861
1862 processing_dispatchers_ = false;
1863 // Process deferred dispatchers that have been added/removed while the
1864 // events were handled above.
1865 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001866 }
1867
1868 // Which is shorter, the delay wait or the asked wait?
1869
Honghai Zhang82d78622016-05-06 11:29:15 -07001870 int64_t cmsNext;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001871 if (cmsWait == kForever) {
1872 cmsNext = cmsWait;
1873 } else {
Honghai Zhang82d78622016-05-06 11:29:15 -07001874 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001875 }
1876
1877 // Wait for one of the events to signal
1878 DWORD dw = WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()),
1879 &events[0],
1880 false,
Honghai Zhang82d78622016-05-06 11:29:15 -07001881 static_cast<DWORD>(cmsNext),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001882 false);
1883
1884 if (dw == WSA_WAIT_FAILED) {
1885 // Failed?
jbauch095ae152015-12-18 01:39:55 -08001886 // TODO(pthatcher): need a better strategy than this!
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001887 WSAGetLastError();
nissec80e7412017-01-11 05:56:46 -08001888 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001889 return false;
1890 } else if (dw == WSA_WAIT_TIMEOUT) {
1891 // Timeout?
1892 return true;
1893 } else {
1894 // Figure out which one it is and call it
1895 CritScope cr(&crit_);
1896 int index = dw - WSA_WAIT_EVENT_0;
1897 if (index > 0) {
1898 --index; // The first event is the socket event
jbauchde4db112017-05-31 13:09:18 -07001899 Dispatcher* disp = event_owners[index];
1900 // The dispatcher could have been removed while waiting for events.
1901 if (dispatchers_.find(disp) != dispatchers_.end()) {
1902 disp->OnPreEvent(0);
1903 disp->OnEvent(0, 0);
1904 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001905 } else if (process_io) {
jbauchde4db112017-05-31 13:09:18 -07001906 processing_dispatchers_ = true;
1907 for (Dispatcher* disp : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001908 SOCKET s = disp->GetSocket();
1909 if (s == INVALID_SOCKET)
1910 continue;
1911
1912 WSANETWORKEVENTS wsaEvents;
1913 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1914 if (err == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001915 {
1916 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1917 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001918 RTC_LOG(WARNING)
1919 << "PhysicalSocketServer got FD_READ_BIT error "
1920 << wsaEvents.iErrorCode[FD_READ_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001921 }
1922 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1923 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001924 RTC_LOG(WARNING)
1925 << "PhysicalSocketServer got FD_WRITE_BIT error "
1926 << wsaEvents.iErrorCode[FD_WRITE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001927 }
1928 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1929 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001930 RTC_LOG(WARNING)
1931 << "PhysicalSocketServer got FD_CONNECT_BIT error "
1932 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001933 }
1934 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1935 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001936 RTC_LOG(WARNING)
1937 << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1938 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001939 }
1940 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1941 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001942 RTC_LOG(WARNING)
1943 << "PhysicalSocketServer got FD_CLOSE_BIT error "
1944 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001945 }
1946 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001947 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001948 int errcode = 0;
1949 if (wsaEvents.lNetworkEvents & FD_READ)
1950 ff |= DE_READ;
1951 if (wsaEvents.lNetworkEvents & FD_WRITE)
1952 ff |= DE_WRITE;
1953 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1954 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1955 ff |= DE_CONNECT;
1956 } else {
1957 ff |= DE_CLOSE;
1958 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1959 }
1960 }
1961 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1962 ff |= DE_ACCEPT;
1963 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1964 ff |= DE_CLOSE;
1965 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1966 }
1967 if (ff != 0) {
1968 disp->OnPreEvent(ff);
1969 disp->OnEvent(ff, errcode);
1970 }
1971 }
1972 }
jbauchde4db112017-05-31 13:09:18 -07001973
1974 processing_dispatchers_ = false;
1975 // Process deferred dispatchers that have been added/removed while the
1976 // events were handled above.
1977 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001978 }
1979
1980 // Reset the network event until new activity occurs
1981 WSAResetEvent(socket_ev_);
1982 }
1983
1984 // Break?
1985 if (!fWait_)
1986 break;
1987 cmsElapsed = TimeSince(msStart);
1988 if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
1989 break;
1990 }
1991 }
1992
1993 // Done
1994 return true;
1995}
honghaizcec0a082016-01-15 14:49:09 -08001996#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001997
1998} // namespace rtc