blob: c1d6d26acc631dcc842552d6d80446de518b804e [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
Steve Anton10542f22019-01-11 09:11:00 -080010#include "rtc_base/physical_socket_server.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000011
12#if defined(_MSC_VER) && _MSC_VER < 1300
Yves Gerey665174f2018-06-19 15:03:05 +020013#pragma warning(disable : 4786)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000014#endif
15
pbos@webrtc.org27e58982014-10-07 17:56:53 +000016#ifdef MEMORY_SANITIZER
17#include <sanitizer/msan_interface.h>
18#endif
19
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000020#if defined(WEBRTC_POSIX)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000021#include <fcntl.h>
Yves Gerey665174f2018-06-19 15:03:05 +020022#include <string.h>
jbauchde4db112017-05-31 13:09:18 -070023#if defined(WEBRTC_USE_EPOLL)
24// "poll" will be used to wait for the signal dispatcher.
25#include <poll.h>
26#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000027#include <signal.h>
Yves Gerey665174f2018-06-19 15:03:05 +020028#include <sys/ioctl.h>
29#include <sys/select.h>
30#include <sys/time.h>
31#include <unistd.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000032#endif
33
34#if defined(WEBRTC_WIN)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000035#include <windows.h>
36#include <winsock2.h>
37#include <ws2tcpip.h>
38#undef SetPort
39#endif
40
Patrik Höglunda8005cf2017-12-13 16:05:42 +010041#include <errno.h>
42
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000043#include <algorithm>
44#include <map>
45
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020046#include "rtc_base/arraysize.h"
Steve Anton10542f22019-01-11 09:11:00 -080047#include "rtc_base/byte_order.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "rtc_base/checks.h"
49#include "rtc_base/logging.h"
Steve Anton10542f22019-01-11 09:11:00 -080050#include "rtc_base/network_monitor.h"
51#include "rtc_base/null_socket_server.h"
52#include "rtc_base/time_utils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000053
Emilio Cobos Álvarez68065502019-05-29 15:30:32 +020054#if defined(WEBRTC_LINUX)
55#include <linux/sockios.h>
56#endif
57
Patrik Höglunda8005cf2017-12-13 16:05:42 +010058#if defined(WEBRTC_WIN)
59#define LAST_SYSTEM_ERROR (::GetLastError())
60#elif defined(__native_client__) && __native_client__
61#define LAST_SYSTEM_ERROR (0)
62#elif defined(WEBRTC_POSIX)
63#define LAST_SYSTEM_ERROR (errno)
64#endif // WEBRTC_WIN
65
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000066#if defined(WEBRTC_POSIX)
67#include <netinet/tcp.h> // for TCP_NODELAY
Yves Gerey665174f2018-06-19 15:03:05 +020068#define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000069typedef void* SockOptArg;
Stefan Holmer9131efd2016-05-23 18:19:26 +020070
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000071#endif // WEBRTC_POSIX
72
Stefan Holmer3ebb3ef2016-05-23 20:26:11 +020073#if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) && !defined(__native_client__)
74
Stefan Holmer9131efd2016-05-23 18:19:26 +020075int64_t GetSocketRecvTimestamp(int socket) {
76 struct timeval tv_ioctl;
77 int ret = ioctl(socket, SIOCGSTAMP, &tv_ioctl);
78 if (ret != 0)
79 return -1;
80 int64_t timestamp =
81 rtc::kNumMicrosecsPerSec * static_cast<int64_t>(tv_ioctl.tv_sec) +
82 static_cast<int64_t>(tv_ioctl.tv_usec);
83 return timestamp;
84}
85
86#else
87
88int64_t GetSocketRecvTimestamp(int socket) {
89 return -1;
90}
91#endif
92
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000093#if defined(WEBRTC_WIN)
94typedef char* SockOptArg;
95#endif
96
jbauchde4db112017-05-31 13:09:18 -070097#if defined(WEBRTC_USE_EPOLL)
98// POLLRDHUP / EPOLLRDHUP are only defined starting with Linux 2.6.17.
99#if !defined(POLLRDHUP)
100#define POLLRDHUP 0x2000
101#endif
102#if !defined(EPOLLRDHUP)
103#define EPOLLRDHUP 0x2000
104#endif
105#endif
106
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000107namespace rtc {
108
danilchapbebf54c2016-04-28 01:32:48 -0700109std::unique_ptr<SocketServer> SocketServer::CreateDefault() {
110#if defined(__native_client__)
111 return std::unique_ptr<SocketServer>(new rtc::NullSocketServer);
112#else
113 return std::unique_ptr<SocketServer>(new rtc::PhysicalSocketServer);
114#endif
115}
116
jbauch095ae152015-12-18 01:39:55 -0800117PhysicalSocket::PhysicalSocket(PhysicalSocketServer* ss, SOCKET s)
Yves Gerey665174f2018-06-19 15:03:05 +0200118 : ss_(ss),
119 s_(s),
120 error_(0),
121 state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED),
122 resolver_(nullptr) {
jbauch095ae152015-12-18 01:39:55 -0800123 if (s_ != INVALID_SOCKET) {
jbauch577f5dc2017-05-17 16:32:26 -0700124 SetEnabledEvents(DE_READ | DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000125
jbauch095ae152015-12-18 01:39:55 -0800126 int type = SOCK_STREAM;
127 socklen_t len = sizeof(type);
nissec16fa5e2017-02-07 07:18:43 -0800128 const int res =
129 getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len);
130 RTC_DCHECK_EQ(0, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000131 udp_ = (SOCK_DGRAM == type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000132 }
jbauch095ae152015-12-18 01:39:55 -0800133}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000134
jbauch095ae152015-12-18 01:39:55 -0800135PhysicalSocket::~PhysicalSocket() {
136 Close();
137}
138
139bool PhysicalSocket::Create(int family, int type) {
140 Close();
141 s_ = ::socket(family, type, 0);
142 udp_ = (SOCK_DGRAM == type);
143 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700144 if (udp_) {
145 SetEnabledEvents(DE_READ | DE_WRITE);
146 }
jbauch095ae152015-12-18 01:39:55 -0800147 return s_ != INVALID_SOCKET;
148}
149
150SocketAddress PhysicalSocket::GetLocalAddress() const {
151 sockaddr_storage addr_storage = {0};
152 socklen_t addrlen = sizeof(addr_storage);
153 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
154 int result = ::getsockname(s_, addr, &addrlen);
155 SocketAddress address;
156 if (result >= 0) {
157 SocketAddressFromSockAddrStorage(addr_storage, &address);
158 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100159 RTC_LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
160 << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000161 }
jbauch095ae152015-12-18 01:39:55 -0800162 return address;
163}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000164
jbauch095ae152015-12-18 01:39:55 -0800165SocketAddress PhysicalSocket::GetRemoteAddress() const {
166 sockaddr_storage addr_storage = {0};
167 socklen_t addrlen = sizeof(addr_storage);
168 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
169 int result = ::getpeername(s_, addr, &addrlen);
170 SocketAddress address;
171 if (result >= 0) {
172 SocketAddressFromSockAddrStorage(addr_storage, &address);
173 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100174 RTC_LOG(LS_WARNING)
175 << "GetRemoteAddress: unable to get remote addr, socket=" << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000176 }
jbauch095ae152015-12-18 01:39:55 -0800177 return address;
178}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000179
jbauch095ae152015-12-18 01:39:55 -0800180int PhysicalSocket::Bind(const SocketAddress& bind_addr) {
deadbeefc874d122017-02-13 15:41:59 -0800181 SocketAddress copied_bind_addr = bind_addr;
182 // If a network binder is available, use it to bind a socket to an interface
183 // instead of bind(), since this is more reliable on an OS with a weak host
184 // model.
deadbeef9ffa13f2017-02-21 16:18:00 -0800185 if (ss_->network_binder() && !bind_addr.IsAnyIP()) {
deadbeefc874d122017-02-13 15:41:59 -0800186 NetworkBindingResult result =
187 ss_->network_binder()->BindSocketToNetwork(s_, bind_addr.ipaddr());
188 if (result == NetworkBindingResult::SUCCESS) {
189 // Since the network binder handled binding the socket to the desired
190 // network interface, we don't need to (and shouldn't) include an IP in
191 // the bind() call; bind() just needs to assign a port.
192 copied_bind_addr.SetIP(GetAnyIP(copied_bind_addr.ipaddr().family()));
193 } else if (result == NetworkBindingResult::NOT_IMPLEMENTED) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100194 RTC_LOG(LS_INFO) << "Can't bind socket to network because "
195 "network binding is not implemented for this OS.";
deadbeefc874d122017-02-13 15:41:59 -0800196 } else {
197 if (bind_addr.IsLoopbackIP()) {
198 // If we couldn't bind to a loopback IP (which should only happen in
199 // test scenarios), continue on. This may be expected behavior.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100200 RTC_LOG(LS_VERBOSE) << "Binding socket to loopback address "
201 << bind_addr.ipaddr().ToString()
202 << " failed; result: " << static_cast<int>(result);
deadbeefc874d122017-02-13 15:41:59 -0800203 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100204 RTC_LOG(LS_WARNING) << "Binding socket to network address "
205 << bind_addr.ipaddr().ToString()
206 << " failed; result: " << static_cast<int>(result);
deadbeefc874d122017-02-13 15:41:59 -0800207 // If a network binding was attempted and failed, we should stop here
208 // and not try to use the socket. Otherwise, we may end up sending
209 // packets with an invalid source address.
210 // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=7026
211 return -1;
212 }
213 }
214 }
jbauch095ae152015-12-18 01:39:55 -0800215 sockaddr_storage addr_storage;
deadbeefc874d122017-02-13 15:41:59 -0800216 size_t len = copied_bind_addr.ToSockAddrStorage(&addr_storage);
jbauch095ae152015-12-18 01:39:55 -0800217 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
218 int err = ::bind(s_, addr, static_cast<int>(len));
219 UpdateLastError();
tfarinaa41ab932015-10-30 16:08:48 -0700220#if !defined(NDEBUG)
jbauch095ae152015-12-18 01:39:55 -0800221 if (0 == err) {
222 dbg_addr_ = "Bound @ ";
223 dbg_addr_.append(GetLocalAddress().ToString());
224 }
tfarinaa41ab932015-10-30 16:08:48 -0700225#endif
jbauch095ae152015-12-18 01:39:55 -0800226 return err;
227}
228
229int PhysicalSocket::Connect(const SocketAddress& addr) {
230 // TODO(pthatcher): Implicit creation is required to reconnect...
231 // ...but should we make it more explicit?
232 if (state_ != CS_CLOSED) {
233 SetError(EALREADY);
234 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000235 }
jbauch095ae152015-12-18 01:39:55 -0800236 if (addr.IsUnresolvedIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100237 RTC_LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
jbauch095ae152015-12-18 01:39:55 -0800238 resolver_ = new AsyncResolver();
239 resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult);
240 resolver_->Start(addr);
241 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000242 return 0;
243 }
244
jbauch095ae152015-12-18 01:39:55 -0800245 return DoConnect(addr);
246}
247
248int PhysicalSocket::DoConnect(const SocketAddress& connect_addr) {
Yves Gerey665174f2018-06-19 15:03:05 +0200249 if ((s_ == INVALID_SOCKET) && !Create(connect_addr.family(), SOCK_STREAM)) {
jbauch095ae152015-12-18 01:39:55 -0800250 return SOCKET_ERROR;
251 }
252 sockaddr_storage addr_storage;
253 size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
254 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
255 int err = ::connect(s_, addr, static_cast<int>(len));
256 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700257 uint8_t events = DE_READ | DE_WRITE;
jbauch095ae152015-12-18 01:39:55 -0800258 if (err == 0) {
259 state_ = CS_CONNECTED;
260 } else if (IsBlockingError(GetError())) {
261 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700262 events |= DE_CONNECT;
jbauch095ae152015-12-18 01:39:55 -0800263 } else {
264 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000265 }
266
jbauch577f5dc2017-05-17 16:32:26 -0700267 EnableEvents(events);
jbauch095ae152015-12-18 01:39:55 -0800268 return 0;
269}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000270
jbauch095ae152015-12-18 01:39:55 -0800271int PhysicalSocket::GetError() const {
272 CritScope cs(&crit_);
273 return error_;
274}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000275
jbauch095ae152015-12-18 01:39:55 -0800276void PhysicalSocket::SetError(int error) {
277 CritScope cs(&crit_);
278 error_ = error;
279}
280
281AsyncSocket::ConnState PhysicalSocket::GetState() const {
282 return state_;
283}
284
285int PhysicalSocket::GetOption(Option opt, int* value) {
286 int slevel;
287 int sopt;
288 if (TranslateOption(opt, &slevel, &sopt) == -1)
289 return -1;
290 socklen_t optlen = sizeof(*value);
291 int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
292 if (ret != -1 && opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000293#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800294 *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000295#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000296 }
jbauch095ae152015-12-18 01:39:55 -0800297 return ret;
298}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000299
jbauch095ae152015-12-18 01:39:55 -0800300int PhysicalSocket::SetOption(Option opt, int value) {
301 int slevel;
302 int sopt;
303 if (TranslateOption(opt, &slevel, &sopt) == -1)
304 return -1;
305 if (opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000306#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800307 value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000308#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000309 }
jbauch095ae152015-12-18 01:39:55 -0800310 return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
311}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000312
jbauch095ae152015-12-18 01:39:55 -0800313int PhysicalSocket::Send(const void* pv, size_t cb) {
Yves Gerey665174f2018-06-19 15:03:05 +0200314 int sent = DoSend(
315 s_, reinterpret_cast<const char*>(pv), static_cast<int>(cb),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000316#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800317 // Suppress SIGPIPE. Without this, attempting to send on a socket whose
318 // other end is closed will result in a SIGPIPE signal being raised to
319 // our process, which by default will terminate the process, which we
320 // don't want. By specifying this flag, we'll just get the error EPIPE
321 // instead and can handle the error gracefully.
322 MSG_NOSIGNAL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000323#else
jbauch095ae152015-12-18 01:39:55 -0800324 0
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000325#endif
Jonas Olssona4d87372019-07-05 19:08:33 +0200326 );
jbauch095ae152015-12-18 01:39:55 -0800327 UpdateLastError();
328 MaybeRemapSendError();
329 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800330 RTC_DCHECK(sent <= static_cast<int>(cb));
jbauchf2a2bf42016-02-03 16:45:32 -0800331 if ((sent > 0 && sent < static_cast<int>(cb)) ||
332 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700333 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000334 }
jbauch095ae152015-12-18 01:39:55 -0800335 return sent;
336}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000337
jbauch095ae152015-12-18 01:39:55 -0800338int PhysicalSocket::SendTo(const void* buffer,
339 size_t length,
340 const SocketAddress& addr) {
341 sockaddr_storage saddr;
342 size_t len = addr.ToSockAddrStorage(&saddr);
Yves Gerey665174f2018-06-19 15:03:05 +0200343 int sent =
344 DoSendTo(s_, static_cast<const char*>(buffer), static_cast<int>(length),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000345#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
Yves Gerey665174f2018-06-19 15:03:05 +0200346 // Suppress SIGPIPE. See above for explanation.
347 MSG_NOSIGNAL,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000348#else
Yves Gerey665174f2018-06-19 15:03:05 +0200349 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000350#endif
Yves Gerey665174f2018-06-19 15:03:05 +0200351 reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
jbauch095ae152015-12-18 01:39:55 -0800352 UpdateLastError();
353 MaybeRemapSendError();
354 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800355 RTC_DCHECK(sent <= static_cast<int>(length));
jbauchf2a2bf42016-02-03 16:45:32 -0800356 if ((sent > 0 && sent < static_cast<int>(length)) ||
357 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700358 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000359 }
jbauch095ae152015-12-18 01:39:55 -0800360 return sent;
361}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000362
Stefan Holmer9131efd2016-05-23 18:19:26 +0200363int PhysicalSocket::Recv(void* buffer, size_t length, int64_t* timestamp) {
Yves Gerey665174f2018-06-19 15:03:05 +0200364 int received =
365 ::recv(s_, static_cast<char*>(buffer), static_cast<int>(length), 0);
jbauch095ae152015-12-18 01:39:55 -0800366 if ((received == 0) && (length != 0)) {
367 // Note: on graceful shutdown, recv can return 0. In this case, we
368 // pretend it is blocking, and then signal close, so that simplifying
369 // assumptions can be made about Recv.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100370 RTC_LOG(LS_WARNING) << "EOF from socket; deferring close event";
jbauch095ae152015-12-18 01:39:55 -0800371 // Must turn this back on so that the select() loop will notice the close
372 // event.
jbauch577f5dc2017-05-17 16:32:26 -0700373 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800374 SetError(EWOULDBLOCK);
375 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000376 }
Stefan Holmer9131efd2016-05-23 18:19:26 +0200377 if (timestamp) {
378 *timestamp = GetSocketRecvTimestamp(s_);
379 }
jbauch095ae152015-12-18 01:39:55 -0800380 UpdateLastError();
381 int error = GetError();
382 bool success = (received >= 0) || IsBlockingError(error);
383 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700384 EnableEvents(DE_READ);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000385 }
jbauch095ae152015-12-18 01:39:55 -0800386 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100387 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000388 }
jbauch095ae152015-12-18 01:39:55 -0800389 return received;
390}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000391
jbauch095ae152015-12-18 01:39:55 -0800392int PhysicalSocket::RecvFrom(void* buffer,
393 size_t length,
Stefan Holmer9131efd2016-05-23 18:19:26 +0200394 SocketAddress* out_addr,
395 int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800396 sockaddr_storage addr_storage;
397 socklen_t addr_len = sizeof(addr_storage);
398 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
399 int received = ::recvfrom(s_, static_cast<char*>(buffer),
400 static_cast<int>(length), 0, addr, &addr_len);
Stefan Holmer9131efd2016-05-23 18:19:26 +0200401 if (timestamp) {
402 *timestamp = GetSocketRecvTimestamp(s_);
403 }
jbauch095ae152015-12-18 01:39:55 -0800404 UpdateLastError();
405 if ((received >= 0) && (out_addr != nullptr))
406 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
407 int error = GetError();
408 bool success = (received >= 0) || IsBlockingError(error);
409 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700410 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800411 }
412 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100413 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
jbauch095ae152015-12-18 01:39:55 -0800414 }
415 return received;
416}
417
418int PhysicalSocket::Listen(int backlog) {
419 int err = ::listen(s_, backlog);
420 UpdateLastError();
421 if (err == 0) {
422 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700423 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800424#if !defined(NDEBUG)
425 dbg_addr_ = "Listening @ ";
426 dbg_addr_.append(GetLocalAddress().ToString());
427#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000428 }
jbauch095ae152015-12-18 01:39:55 -0800429 return err;
430}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000431
jbauch095ae152015-12-18 01:39:55 -0800432AsyncSocket* PhysicalSocket::Accept(SocketAddress* out_addr) {
433 // Always re-subscribe DE_ACCEPT to make sure new incoming connections will
434 // trigger an event even if DoAccept returns an error here.
jbauch577f5dc2017-05-17 16:32:26 -0700435 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800436 sockaddr_storage addr_storage;
437 socklen_t addr_len = sizeof(addr_storage);
438 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
439 SOCKET s = DoAccept(s_, addr, &addr_len);
440 UpdateLastError();
441 if (s == INVALID_SOCKET)
442 return nullptr;
443 if (out_addr != nullptr)
444 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
445 return ss_->WrapSocket(s);
446}
447
448int PhysicalSocket::Close() {
449 if (s_ == INVALID_SOCKET)
450 return 0;
451 int err = ::closesocket(s_);
452 UpdateLastError();
453 s_ = INVALID_SOCKET;
454 state_ = CS_CLOSED;
jbauch577f5dc2017-05-17 16:32:26 -0700455 SetEnabledEvents(0);
jbauch095ae152015-12-18 01:39:55 -0800456 if (resolver_) {
457 resolver_->Destroy(false);
458 resolver_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000459 }
jbauch095ae152015-12-18 01:39:55 -0800460 return err;
461}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000462
jbauch095ae152015-12-18 01:39:55 -0800463SOCKET PhysicalSocket::DoAccept(SOCKET socket,
464 sockaddr* addr,
465 socklen_t* addrlen) {
466 return ::accept(socket, addr, addrlen);
467}
468
jbauchf2a2bf42016-02-03 16:45:32 -0800469int PhysicalSocket::DoSend(SOCKET socket, const char* buf, int len, int flags) {
470 return ::send(socket, buf, len, flags);
471}
472
473int PhysicalSocket::DoSendTo(SOCKET socket,
474 const char* buf,
475 int len,
476 int flags,
477 const struct sockaddr* dest_addr,
478 socklen_t addrlen) {
479 return ::sendto(socket, buf, len, flags, dest_addr, addrlen);
480}
481
jbauch095ae152015-12-18 01:39:55 -0800482void PhysicalSocket::OnResolveResult(AsyncResolverInterface* resolver) {
483 if (resolver != resolver_) {
484 return;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000485 }
486
jbauch095ae152015-12-18 01:39:55 -0800487 int error = resolver_->GetError();
488 if (error == 0) {
489 error = DoConnect(resolver_->address());
490 } else {
491 Close();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000492 }
493
jbauch095ae152015-12-18 01:39:55 -0800494 if (error) {
495 SetError(error);
496 SignalCloseEvent(this, error);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000497 }
jbauch095ae152015-12-18 01:39:55 -0800498}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000499
jbauch095ae152015-12-18 01:39:55 -0800500void PhysicalSocket::UpdateLastError() {
Patrik Höglunda8005cf2017-12-13 16:05:42 +0100501 SetError(LAST_SYSTEM_ERROR);
jbauch095ae152015-12-18 01:39:55 -0800502}
503
504void PhysicalSocket::MaybeRemapSendError() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000505#if defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800506 // https://developer.apple.com/library/mac/documentation/Darwin/
507 // Reference/ManPages/man2/sendto.2.html
508 // ENOBUFS - The output queue for a network interface is full.
509 // This generally indicates that the interface has stopped sending,
510 // but may be caused by transient congestion.
511 if (GetError() == ENOBUFS) {
512 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000513 }
jbauch095ae152015-12-18 01:39:55 -0800514#endif
515}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000516
jbauch577f5dc2017-05-17 16:32:26 -0700517void PhysicalSocket::SetEnabledEvents(uint8_t events) {
518 enabled_events_ = events;
519}
520
521void PhysicalSocket::EnableEvents(uint8_t events) {
522 enabled_events_ |= events;
523}
524
525void PhysicalSocket::DisableEvents(uint8_t events) {
526 enabled_events_ &= ~events;
527}
528
jbauch095ae152015-12-18 01:39:55 -0800529int PhysicalSocket::TranslateOption(Option opt, int* slevel, int* sopt) {
530 switch (opt) {
531 case OPT_DONTFRAGMENT:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000532#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800533 *slevel = IPPROTO_IP;
534 *sopt = IP_DONTFRAGMENT;
535 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000536#elif defined(WEBRTC_MAC) || defined(BSD) || defined(__native_client__)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100537 RTC_LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
jbauch095ae152015-12-18 01:39:55 -0800538 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000539#elif defined(WEBRTC_POSIX)
jbauch095ae152015-12-18 01:39:55 -0800540 *slevel = IPPROTO_IP;
541 *sopt = IP_MTU_DISCOVER;
542 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000543#endif
jbauch095ae152015-12-18 01:39:55 -0800544 case OPT_RCVBUF:
545 *slevel = SOL_SOCKET;
546 *sopt = SO_RCVBUF;
547 break;
548 case OPT_SNDBUF:
549 *slevel = SOL_SOCKET;
550 *sopt = SO_SNDBUF;
551 break;
552 case OPT_NODELAY:
553 *slevel = IPPROTO_TCP;
554 *sopt = TCP_NODELAY;
555 break;
556 case OPT_DSCP:
Mirko Bonadei675513b2017-11-09 11:09:25 +0100557 RTC_LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
jbauch095ae152015-12-18 01:39:55 -0800558 return -1;
559 case OPT_RTP_SENDTIME_EXTN_ID:
560 return -1; // No logging is necessary as this not a OS socket option.
561 default:
nissec80e7412017-01-11 05:56:46 -0800562 RTC_NOTREACHED();
jbauch095ae152015-12-18 01:39:55 -0800563 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000564 }
jbauch095ae152015-12-18 01:39:55 -0800565 return 0;
566}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000567
Yves Gerey665174f2018-06-19 15:03:05 +0200568SocketDispatcher::SocketDispatcher(PhysicalSocketServer* ss)
jbauch4331fcd2016-01-06 22:20:28 -0800569#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200570 : PhysicalSocket(ss),
571 id_(0),
572 signal_close_(false)
jbauch4331fcd2016-01-06 22:20:28 -0800573#else
Yves Gerey665174f2018-06-19 15:03:05 +0200574 : PhysicalSocket(ss)
jbauch4331fcd2016-01-06 22:20:28 -0800575#endif
576{
577}
578
Yves Gerey665174f2018-06-19 15:03:05 +0200579SocketDispatcher::SocketDispatcher(SOCKET s, PhysicalSocketServer* ss)
jbauch4331fcd2016-01-06 22:20:28 -0800580#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200581 : PhysicalSocket(ss, s),
582 id_(0),
583 signal_close_(false)
jbauch4331fcd2016-01-06 22:20:28 -0800584#else
Yves Gerey665174f2018-06-19 15:03:05 +0200585 : PhysicalSocket(ss, s)
jbauch4331fcd2016-01-06 22:20:28 -0800586#endif
587{
588}
589
590SocketDispatcher::~SocketDispatcher() {
591 Close();
592}
593
594bool SocketDispatcher::Initialize() {
nisseede5da42017-01-12 05:15:36 -0800595 RTC_DCHECK(s_ != INVALID_SOCKET);
Yves Gerey665174f2018-06-19 15:03:05 +0200596// Must be a non-blocking
jbauch4331fcd2016-01-06 22:20:28 -0800597#if defined(WEBRTC_WIN)
598 u_long argp = 1;
599 ioctlsocket(s_, FIONBIO, &argp);
600#elif defined(WEBRTC_POSIX)
601 fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
602#endif
deadbeefeae45642017-05-26 16:27:09 -0700603#if defined(WEBRTC_IOS)
604 // iOS may kill sockets when the app is moved to the background
605 // (specifically, if the app doesn't use the "voip" UIBackgroundMode). When
606 // we attempt to write to such a socket, SIGPIPE will be raised, which by
607 // default will terminate the process, which we don't want. By specifying
608 // this socket option, SIGPIPE will be disabled for the socket.
609 int value = 1;
610 ::setsockopt(s_, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value));
611#endif
jbauch4331fcd2016-01-06 22:20:28 -0800612 ss_->Add(this);
613 return true;
614}
615
616bool SocketDispatcher::Create(int type) {
617 return Create(AF_INET, type);
618}
619
620bool SocketDispatcher::Create(int family, int type) {
621 // Change the socket to be non-blocking.
622 if (!PhysicalSocket::Create(family, type))
623 return false;
624
625 if (!Initialize())
626 return false;
627
628#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200629 do {
630 id_ = ++next_id_;
631 } while (id_ == 0);
jbauch4331fcd2016-01-06 22:20:28 -0800632#endif
633 return true;
634}
635
636#if defined(WEBRTC_WIN)
637
638WSAEVENT SocketDispatcher::GetWSAEvent() {
639 return WSA_INVALID_EVENT;
640}
641
642SOCKET SocketDispatcher::GetSocket() {
643 return s_;
644}
645
646bool SocketDispatcher::CheckSignalClose() {
647 if (!signal_close_)
648 return false;
649
650 char ch;
651 if (recv(s_, &ch, 1, MSG_PEEK) > 0)
652 return false;
653
654 state_ = CS_CLOSED;
655 signal_close_ = false;
656 SignalCloseEvent(this, signal_err_);
657 return true;
658}
659
660int SocketDispatcher::next_id_ = 0;
661
662#elif defined(WEBRTC_POSIX)
663
664int SocketDispatcher::GetDescriptor() {
665 return s_;
666}
667
668bool SocketDispatcher::IsDescriptorClosed() {
deadbeeffaedf7f2017-02-09 15:09:22 -0800669 if (udp_) {
670 // The MSG_PEEK trick doesn't work for UDP, since (at least in some
671 // circumstances) it requires reading an entire UDP packet, which would be
672 // bad for performance here. So, just check whether |s_| has been closed,
673 // which should be sufficient.
674 return s_ == INVALID_SOCKET;
675 }
jbauch4331fcd2016-01-06 22:20:28 -0800676 // We don't have a reliable way of distinguishing end-of-stream
677 // from readability. So test on each readable call. Is this
678 // inefficient? Probably.
679 char ch;
680 ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
681 if (res > 0) {
682 // Data available, so not closed.
683 return false;
684 } else if (res == 0) {
685 // EOF, so closed.
686 return true;
687 } else { // error
688 switch (errno) {
689 // Returned if we've already closed s_.
690 case EBADF:
691 // Returned during ungraceful peer shutdown.
692 case ECONNRESET:
693 return true;
deadbeeffaedf7f2017-02-09 15:09:22 -0800694 // The normal blocking error; don't log anything.
695 case EWOULDBLOCK:
696 // Interrupted system call.
697 case EINTR:
698 return false;
jbauch4331fcd2016-01-06 22:20:28 -0800699 default:
700 // Assume that all other errors are just blocking errors, meaning the
701 // connection is still good but we just can't read from it right now.
702 // This should only happen when connecting (and at most once), because
703 // in all other cases this function is only called if the file
704 // descriptor is already known to be in the readable state. However,
705 // it's not necessary a problem if we spuriously interpret a
706 // "connection lost"-type error as a blocking error, because typically
707 // the next recv() will get EOF, so we'll still eventually notice that
708 // the socket is closed.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100709 RTC_LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
jbauch4331fcd2016-01-06 22:20:28 -0800710 return false;
711 }
712 }
713}
714
Yves Gerey665174f2018-06-19 15:03:05 +0200715#endif // WEBRTC_POSIX
jbauch4331fcd2016-01-06 22:20:28 -0800716
717uint32_t SocketDispatcher::GetRequestedEvents() {
jbauch577f5dc2017-05-17 16:32:26 -0700718 return enabled_events();
jbauch4331fcd2016-01-06 22:20:28 -0800719}
720
721void SocketDispatcher::OnPreEvent(uint32_t ff) {
722 if ((ff & DE_CONNECT) != 0)
723 state_ = CS_CONNECTED;
724
725#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200726// We set CS_CLOSED from CheckSignalClose.
jbauch4331fcd2016-01-06 22:20:28 -0800727#elif defined(WEBRTC_POSIX)
728 if ((ff & DE_CLOSE) != 0)
729 state_ = CS_CLOSED;
730#endif
731}
732
733#if defined(WEBRTC_WIN)
734
735void SocketDispatcher::OnEvent(uint32_t ff, int err) {
736 int cache_id = id_;
737 // Make sure we deliver connect/accept first. Otherwise, consumers may see
738 // something like a READ followed by a CONNECT, which would be odd.
739 if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
740 if (ff != DE_CONNECT)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100741 RTC_LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
jbauch577f5dc2017-05-17 16:32:26 -0700742 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800743#if !defined(NDEBUG)
744 dbg_addr_ = "Connected @ ";
745 dbg_addr_.append(GetRemoteAddress().ToString());
746#endif
747 SignalConnectEvent(this);
748 }
749 if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700750 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800751 SignalReadEvent(this);
752 }
753 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700754 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800755 SignalReadEvent(this);
756 }
757 if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700758 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800759 SignalWriteEvent(this);
760 }
761 if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
762 signal_close_ = true;
763 signal_err_ = err;
764 }
765}
766
767#elif defined(WEBRTC_POSIX)
768
769void SocketDispatcher::OnEvent(uint32_t ff, int err) {
jbauchde4db112017-05-31 13:09:18 -0700770#if defined(WEBRTC_USE_EPOLL)
771 // Remember currently enabled events so we can combine multiple changes
772 // into one update call later.
773 // The signal handlers might re-enable events disabled here, so we can't
774 // keep a list of events to disable at the end of the method. This list
775 // would not be updated with the events enabled by the signal handlers.
776 StartBatchedEventUpdates();
777#endif
jbauch4331fcd2016-01-06 22:20:28 -0800778 // Make sure we deliver connect/accept first. Otherwise, consumers may see
779 // something like a READ followed by a CONNECT, which would be odd.
780 if ((ff & DE_CONNECT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700781 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800782 SignalConnectEvent(this);
783 }
784 if ((ff & DE_ACCEPT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700785 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800786 SignalReadEvent(this);
787 }
788 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700789 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800790 SignalReadEvent(this);
791 }
792 if ((ff & DE_WRITE) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700793 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800794 SignalWriteEvent(this);
795 }
796 if ((ff & DE_CLOSE) != 0) {
797 // The socket is now dead to us, so stop checking it.
jbauch577f5dc2017-05-17 16:32:26 -0700798 SetEnabledEvents(0);
jbauch4331fcd2016-01-06 22:20:28 -0800799 SignalCloseEvent(this, err);
800 }
jbauchde4db112017-05-31 13:09:18 -0700801#if defined(WEBRTC_USE_EPOLL)
802 FinishBatchedEventUpdates();
803#endif
jbauch4331fcd2016-01-06 22:20:28 -0800804}
805
Yves Gerey665174f2018-06-19 15:03:05 +0200806#endif // WEBRTC_POSIX
jbauch4331fcd2016-01-06 22:20:28 -0800807
jbauchde4db112017-05-31 13:09:18 -0700808#if defined(WEBRTC_USE_EPOLL)
809
810static int GetEpollEvents(uint32_t ff) {
811 int events = 0;
812 if (ff & (DE_READ | DE_ACCEPT)) {
813 events |= EPOLLIN;
814 }
815 if (ff & (DE_WRITE | DE_CONNECT)) {
816 events |= EPOLLOUT;
817 }
818 return events;
819}
820
821void SocketDispatcher::StartBatchedEventUpdates() {
822 RTC_DCHECK_EQ(saved_enabled_events_, -1);
823 saved_enabled_events_ = enabled_events();
824}
825
826void SocketDispatcher::FinishBatchedEventUpdates() {
827 RTC_DCHECK_NE(saved_enabled_events_, -1);
828 uint8_t old_events = static_cast<uint8_t>(saved_enabled_events_);
829 saved_enabled_events_ = -1;
830 MaybeUpdateDispatcher(old_events);
831}
832
833void SocketDispatcher::MaybeUpdateDispatcher(uint8_t old_events) {
834 if (GetEpollEvents(enabled_events()) != GetEpollEvents(old_events) &&
835 saved_enabled_events_ == -1) {
836 ss_->Update(this);
837 }
838}
839
840void SocketDispatcher::SetEnabledEvents(uint8_t events) {
841 uint8_t old_events = enabled_events();
842 PhysicalSocket::SetEnabledEvents(events);
843 MaybeUpdateDispatcher(old_events);
844}
845
846void SocketDispatcher::EnableEvents(uint8_t events) {
847 uint8_t old_events = enabled_events();
848 PhysicalSocket::EnableEvents(events);
849 MaybeUpdateDispatcher(old_events);
850}
851
852void SocketDispatcher::DisableEvents(uint8_t events) {
853 uint8_t old_events = enabled_events();
854 PhysicalSocket::DisableEvents(events);
855 MaybeUpdateDispatcher(old_events);
856}
857
858#endif // WEBRTC_USE_EPOLL
859
jbauch4331fcd2016-01-06 22:20:28 -0800860int SocketDispatcher::Close() {
861 if (s_ == INVALID_SOCKET)
862 return 0;
863
864#if defined(WEBRTC_WIN)
865 id_ = 0;
866 signal_close_ = false;
867#endif
868 ss_->Remove(this);
869 return PhysicalSocket::Close();
870}
871
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000872#if defined(WEBRTC_POSIX)
873class EventDispatcher : public Dispatcher {
874 public:
875 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
876 if (pipe(afd_) < 0)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100877 RTC_LOG(LERROR) << "pipe failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000878 ss_->Add(this);
879 }
880
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000881 ~EventDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000882 ss_->Remove(this);
883 close(afd_[0]);
884 close(afd_[1]);
885 }
886
887 virtual void Signal() {
888 CritScope cs(&crit_);
889 if (!fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200890 const uint8_t b[1] = {0};
nissec16fa5e2017-02-07 07:18:43 -0800891 const ssize_t res = write(afd_[1], b, sizeof(b));
892 RTC_DCHECK_EQ(1, res);
893 fSignaled_ = true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000894 }
895 }
896
Peter Boström0c4e06b2015-10-07 12:23:21 +0200897 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000898
Peter Boström0c4e06b2015-10-07 12:23:21 +0200899 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000900 // It is not possible to perfectly emulate an auto-resetting event with
901 // pipes. This simulates it by resetting before the event is handled.
902
903 CritScope cs(&crit_);
904 if (fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200905 uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
nissec16fa5e2017-02-07 07:18:43 -0800906 const ssize_t res = read(afd_[0], b, sizeof(b));
907 RTC_DCHECK_EQ(1, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000908 fSignaled_ = false;
909 }
910 }
911
nissec80e7412017-01-11 05:56:46 -0800912 void OnEvent(uint32_t ff, int err) override { RTC_NOTREACHED(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000913
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000914 int GetDescriptor() override { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000915
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000916 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000917
918 private:
Yves Gerey665174f2018-06-19 15:03:05 +0200919 PhysicalSocketServer* ss_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000920 int afd_[2];
921 bool fSignaled_;
922 CriticalSection crit_;
923};
924
925// These two classes use the self-pipe trick to deliver POSIX signals to our
926// select loop. This is the only safe, reliable, cross-platform way to do
927// non-trivial things with a POSIX signal in an event-driven program (until
928// proper pselect() implementations become ubiquitous).
929
930class PosixSignalHandler {
931 public:
932 // POSIX only specifies 32 signals, but in principle the system might have
933 // more and the programmer might choose to use them, so we size our array
934 // for 128.
935 static const int kNumPosixSignals = 128;
936
937 // There is just a single global instance. (Signal handlers do not get any
938 // sort of user-defined void * parameter, so they can't access anything that
939 // isn't global.)
940 static PosixSignalHandler* Instance() {
Niels Möller14682a32018-05-24 08:54:25 +0200941 static PosixSignalHandler* const instance = new PosixSignalHandler();
942 return instance;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000943 }
944
945 // Returns true if the given signal number is set.
946 bool IsSignalSet(int signum) const {
nisseede5da42017-01-12 05:15:36 -0800947 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800948 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000949 return received_signal_[signum];
950 } else {
951 return false;
952 }
953 }
954
955 // Clears the given signal number.
956 void ClearSignal(int signum) {
nisseede5da42017-01-12 05:15:36 -0800957 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800958 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000959 received_signal_[signum] = false;
960 }
961 }
962
963 // Returns the file descriptor to monitor for signal events.
Yves Gerey665174f2018-06-19 15:03:05 +0200964 int GetDescriptor() const { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000965
966 // This is called directly from our real signal handler, so it must be
967 // signal-handler-safe. That means it cannot assume anything about the
968 // user-level state of the process, since the handler could be executed at any
969 // time on any thread.
970 void OnPosixSignalReceived(int signum) {
tfarina5237aaf2015-11-10 23:44:30 -0800971 if (signum >= static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000972 // We don't have space in our array for this.
973 return;
974 }
975 // Set a flag saying we've seen this signal.
976 received_signal_[signum] = true;
977 // Notify application code that we got a signal.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200978 const uint8_t b[1] = {0};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000979 if (-1 == write(afd_[1], b, sizeof(b))) {
980 // Nothing we can do here. If there's an error somehow then there's
981 // nothing we can safely do from a signal handler.
982 // No, we can't even safely log it.
983 // But, we still have to check the return value here. Otherwise,
984 // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
985 return;
986 }
987 }
988
989 private:
990 PosixSignalHandler() {
991 if (pipe(afd_) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100992 RTC_LOG_ERR(LS_ERROR) << "pipe failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000993 return;
994 }
995 if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100996 RTC_LOG_ERR(LS_WARNING) << "fcntl #1 failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000997 }
998 if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100999 RTC_LOG_ERR(LS_WARNING) << "fcntl #2 failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001000 }
Yves Gerey665174f2018-06-19 15:03:05 +02001001 memset(const_cast<void*>(static_cast<volatile void*>(received_signal_)), 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001002 sizeof(received_signal_));
1003 }
1004
1005 ~PosixSignalHandler() {
1006 int fd1 = afd_[0];
1007 int fd2 = afd_[1];
1008 // We clobber the stored file descriptor numbers here or else in principle
1009 // a signal that happens to be delivered during application termination
1010 // could erroneously write a zero byte to an unrelated file handle in
1011 // OnPosixSignalReceived() if some other file happens to be opened later
1012 // during shutdown and happens to be given the same file descriptor number
1013 // as our pipe had. Unfortunately even with this precaution there is still a
1014 // race where that could occur if said signal happens to be handled
1015 // concurrently with this code and happens to have already read the value of
1016 // afd_[1] from memory before we clobber it, but that's unlikely.
1017 afd_[0] = -1;
1018 afd_[1] = -1;
1019 close(fd1);
1020 close(fd2);
1021 }
1022
1023 int afd_[2];
1024 // These are boolean flags that will be set in our signal handler and read
1025 // and cleared from Wait(). There is a race involved in this, but it is
1026 // benign. The signal handler sets the flag before signaling the pipe, so
1027 // we'll never end up blocking in select() while a flag is still true.
1028 // However, if two of the same signal arrive close to each other then it's
1029 // possible that the second time the handler may set the flag while it's still
1030 // true, meaning that signal will be missed. But the first occurrence of it
1031 // will still be handled, so this isn't a problem.
1032 // Volatile is not necessary here for correctness, but this data _is_ volatile
1033 // so I've marked it as such.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001034 volatile uint8_t received_signal_[kNumPosixSignals];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001035};
1036
1037class PosixSignalDispatcher : public Dispatcher {
1038 public:
Yves Gerey665174f2018-06-19 15:03:05 +02001039 PosixSignalDispatcher(PhysicalSocketServer* owner) : owner_(owner) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001040 owner_->Add(this);
1041 }
1042
Yves Gerey665174f2018-06-19 15:03:05 +02001043 ~PosixSignalDispatcher() override { owner_->Remove(this); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001044
Peter Boström0c4e06b2015-10-07 12:23:21 +02001045 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001046
Peter Boström0c4e06b2015-10-07 12:23:21 +02001047 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001048 // Events might get grouped if signals come very fast, so we read out up to
1049 // 16 bytes to make sure we keep the pipe empty.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001050 uint8_t b[16];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001051 ssize_t ret = read(GetDescriptor(), b, sizeof(b));
1052 if (ret < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001053 RTC_LOG_ERR(LS_WARNING) << "Error in read()";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001054 } else if (ret == 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001055 RTC_LOG(LS_WARNING) << "Should have read at least one byte";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001056 }
1057 }
1058
Peter Boström0c4e06b2015-10-07 12:23:21 +02001059 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001060 for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
1061 ++signum) {
1062 if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
1063 PosixSignalHandler::Instance()->ClearSignal(signum);
1064 HandlerMap::iterator i = handlers_.find(signum);
1065 if (i == handlers_.end()) {
1066 // This can happen if a signal is delivered to our process at around
1067 // the same time as we unset our handler for it. It is not an error
1068 // condition, but it's unusual enough to be worth logging.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001069 RTC_LOG(LS_INFO) << "Received signal with no handler: " << signum;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001070 } else {
1071 // Otherwise, execute our handler.
1072 (*i->second)(signum);
1073 }
1074 }
1075 }
1076 }
1077
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001078 int GetDescriptor() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001079 return PosixSignalHandler::Instance()->GetDescriptor();
1080 }
1081
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001082 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001083
1084 void SetHandler(int signum, void (*handler)(int)) {
1085 handlers_[signum] = handler;
1086 }
1087
Yves Gerey665174f2018-06-19 15:03:05 +02001088 void ClearHandler(int signum) { handlers_.erase(signum); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001089
Yves Gerey665174f2018-06-19 15:03:05 +02001090 bool HasHandlers() { return !handlers_.empty(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001091
1092 private:
1093 typedef std::map<int, void (*)(int)> HandlerMap;
1094
1095 HandlerMap handlers_;
1096 // Our owner.
Yves Gerey665174f2018-06-19 15:03:05 +02001097 PhysicalSocketServer* owner_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001098};
1099
Yves Gerey665174f2018-06-19 15:03:05 +02001100#endif // WEBRTC_POSIX
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001101
1102#if defined(WEBRTC_WIN)
Peter Boström0c4e06b2015-10-07 12:23:21 +02001103static uint32_t FlagsToEvents(uint32_t events) {
1104 uint32_t ffFD = FD_CLOSE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001105 if (events & DE_READ)
1106 ffFD |= FD_READ;
1107 if (events & DE_WRITE)
1108 ffFD |= FD_WRITE;
1109 if (events & DE_CONNECT)
1110 ffFD |= FD_CONNECT;
1111 if (events & DE_ACCEPT)
1112 ffFD |= FD_ACCEPT;
1113 return ffFD;
1114}
1115
1116class EventDispatcher : public Dispatcher {
1117 public:
Yves Gerey665174f2018-06-19 15:03:05 +02001118 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001119 hev_ = WSACreateEvent();
1120 if (hev_) {
1121 ss_->Add(this);
1122 }
1123 }
1124
Steve Anton9de3aac2017-10-24 10:08:26 -07001125 ~EventDispatcher() override {
deadbeef37f5ecf2017-02-27 14:06:41 -08001126 if (hev_ != nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001127 ss_->Remove(this);
1128 WSACloseEvent(hev_);
deadbeef37f5ecf2017-02-27 14:06:41 -08001129 hev_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001130 }
1131 }
1132
1133 virtual void Signal() {
deadbeef37f5ecf2017-02-27 14:06:41 -08001134 if (hev_ != nullptr)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001135 WSASetEvent(hev_);
1136 }
1137
Steve Anton9de3aac2017-10-24 10:08:26 -07001138 uint32_t GetRequestedEvents() override { return 0; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001139
Steve Anton9de3aac2017-10-24 10:08:26 -07001140 void OnPreEvent(uint32_t ff) override { WSAResetEvent(hev_); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001141
Steve Anton9de3aac2017-10-24 10:08:26 -07001142 void OnEvent(uint32_t ff, int err) override {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001143
Steve Anton9de3aac2017-10-24 10:08:26 -07001144 WSAEVENT GetWSAEvent() override { return hev_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001145
Steve Anton9de3aac2017-10-24 10:08:26 -07001146 SOCKET GetSocket() override { return INVALID_SOCKET; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001147
Steve Anton9de3aac2017-10-24 10:08:26 -07001148 bool CheckSignalClose() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001149
Steve Anton9de3aac2017-10-24 10:08:26 -07001150 private:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001151 PhysicalSocketServer* ss_;
1152 WSAEVENT hev_;
1153};
honghaizcec0a082016-01-15 14:49:09 -08001154#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001155
1156// Sets the value of a boolean value to false when signaled.
1157class Signaler : public EventDispatcher {
1158 public:
Yves Gerey665174f2018-06-19 15:03:05 +02001159 Signaler(PhysicalSocketServer* ss, bool* pf) : EventDispatcher(ss), pf_(pf) {}
1160 ~Signaler() override {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001161
Peter Boström0c4e06b2015-10-07 12:23:21 +02001162 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001163 if (pf_)
1164 *pf_ = false;
1165 }
1166
1167 private:
Yves Gerey665174f2018-06-19 15:03:05 +02001168 bool* pf_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001169};
1170
Yves Gerey665174f2018-06-19 15:03:05 +02001171PhysicalSocketServer::PhysicalSocketServer() : fWait_(false) {
jbauchde4db112017-05-31 13:09:18 -07001172#if defined(WEBRTC_USE_EPOLL)
1173 // Since Linux 2.6.8, the size argument is ignored, but must be greater than
1174 // zero. Before that the size served as hint to the kernel for the amount of
1175 // space to initially allocate in internal data structures.
1176 epoll_fd_ = epoll_create(FD_SETSIZE);
1177 if (epoll_fd_ == -1) {
1178 // Not an error, will fall back to "select" below.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001179 RTC_LOG_E(LS_WARNING, EN, errno) << "epoll_create";
jbauchde4db112017-05-31 13:09:18 -07001180 epoll_fd_ = INVALID_SOCKET;
1181 }
1182#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001183 signal_wakeup_ = new Signaler(this, &fWait_);
1184#if defined(WEBRTC_WIN)
1185 socket_ev_ = WSACreateEvent();
1186#endif
1187}
1188
1189PhysicalSocketServer::~PhysicalSocketServer() {
1190#if defined(WEBRTC_WIN)
1191 WSACloseEvent(socket_ev_);
1192#endif
1193#if defined(WEBRTC_POSIX)
1194 signal_dispatcher_.reset();
1195#endif
1196 delete signal_wakeup_;
jbauchde4db112017-05-31 13:09:18 -07001197#if defined(WEBRTC_USE_EPOLL)
1198 if (epoll_fd_ != INVALID_SOCKET) {
1199 close(epoll_fd_);
1200 }
1201#endif
nisseede5da42017-01-12 05:15:36 -08001202 RTC_DCHECK(dispatchers_.empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001203}
1204
1205void PhysicalSocketServer::WakeUp() {
1206 signal_wakeup_->Signal();
1207}
1208
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001209Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
1210 PhysicalSocket* socket = new PhysicalSocket(this);
1211 if (socket->Create(family, type)) {
1212 return socket;
1213 } else {
1214 delete socket;
jbauch095ae152015-12-18 01:39:55 -08001215 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001216 }
1217}
1218
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001219AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
1220 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1221 if (dispatcher->Create(family, type)) {
1222 return dispatcher;
1223 } else {
1224 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001225 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001226 }
1227}
1228
1229AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
1230 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1231 if (dispatcher->Initialize()) {
1232 return dispatcher;
1233 } else {
1234 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001235 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001236 }
1237}
1238
Yves Gerey665174f2018-06-19 15:03:05 +02001239void PhysicalSocketServer::Add(Dispatcher* pdispatcher) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001240 CritScope cs(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001241 if (processing_dispatchers_) {
1242 // A dispatcher is being added while a "Wait" call is processing the
1243 // list of socket events.
1244 // Defer adding to "dispatchers_" set until processing is done to avoid
1245 // invalidating the iterator in "Wait".
1246 pending_remove_dispatchers_.erase(pdispatcher);
1247 pending_add_dispatchers_.insert(pdispatcher);
1248 } else {
1249 dispatchers_.insert(pdispatcher);
1250 }
1251#if defined(WEBRTC_USE_EPOLL)
1252 if (epoll_fd_ != INVALID_SOCKET) {
1253 AddEpoll(pdispatcher);
1254 }
1255#endif // WEBRTC_USE_EPOLL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001256}
1257
Yves Gerey665174f2018-06-19 15:03:05 +02001258void PhysicalSocketServer::Remove(Dispatcher* pdispatcher) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001259 CritScope cs(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001260 if (processing_dispatchers_) {
1261 // A dispatcher is being removed while a "Wait" call is processing the
1262 // list of socket events.
1263 // Defer removal from "dispatchers_" set until processing is done to avoid
1264 // invalidating the iterator in "Wait".
1265 if (!pending_add_dispatchers_.erase(pdispatcher) &&
1266 dispatchers_.find(pdispatcher) == dispatchers_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001267 RTC_LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
1268 << "dispatcher, potentially from a duplicate call to "
1269 << "Add.";
jbauchde4db112017-05-31 13:09:18 -07001270 return;
1271 }
1272
1273 pending_remove_dispatchers_.insert(pdispatcher);
1274 } else if (!dispatchers_.erase(pdispatcher)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001275 RTC_LOG(LS_WARNING)
1276 << "PhysicalSocketServer asked to remove a unknown "
1277 << "dispatcher, potentially from a duplicate call to Add.";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001278 return;
1279 }
jbauchde4db112017-05-31 13:09:18 -07001280#if defined(WEBRTC_USE_EPOLL)
1281 if (epoll_fd_ != INVALID_SOCKET) {
1282 RemoveEpoll(pdispatcher);
1283 }
1284#endif // WEBRTC_USE_EPOLL
1285}
1286
1287void PhysicalSocketServer::Update(Dispatcher* pdispatcher) {
1288#if defined(WEBRTC_USE_EPOLL)
1289 if (epoll_fd_ == INVALID_SOCKET) {
1290 return;
1291 }
1292
1293 CritScope cs(&crit_);
1294 if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1295 return;
1296 }
1297
1298 UpdateEpoll(pdispatcher);
1299#endif
1300}
1301
1302void PhysicalSocketServer::AddRemovePendingDispatchers() {
1303 if (!pending_add_dispatchers_.empty()) {
1304 for (Dispatcher* pdispatcher : pending_add_dispatchers_) {
1305 dispatchers_.insert(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001306 }
jbauchde4db112017-05-31 13:09:18 -07001307 pending_add_dispatchers_.clear();
1308 }
1309
1310 if (!pending_remove_dispatchers_.empty()) {
1311 for (Dispatcher* pdispatcher : pending_remove_dispatchers_) {
1312 dispatchers_.erase(pdispatcher);
1313 }
1314 pending_remove_dispatchers_.clear();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001315 }
1316}
1317
1318#if defined(WEBRTC_POSIX)
jbauchde4db112017-05-31 13:09:18 -07001319
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001320bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
jbauchde4db112017-05-31 13:09:18 -07001321#if defined(WEBRTC_USE_EPOLL)
1322 // We don't keep a dedicated "epoll" descriptor containing only the non-IO
1323 // (i.e. signaling) dispatcher, so "poll" will be used instead of the default
1324 // "select" to support sockets larger than FD_SETSIZE.
1325 if (!process_io) {
1326 return WaitPoll(cmsWait, signal_wakeup_);
1327 } else if (epoll_fd_ != INVALID_SOCKET) {
1328 return WaitEpoll(cmsWait);
1329 }
1330#endif
1331 return WaitSelect(cmsWait, process_io);
1332}
1333
1334static void ProcessEvents(Dispatcher* dispatcher,
1335 bool readable,
1336 bool writable,
1337 bool check_error) {
1338 int errcode = 0;
1339 // TODO(pthatcher): Should we set errcode if getsockopt fails?
1340 if (check_error) {
1341 socklen_t len = sizeof(errcode);
1342 ::getsockopt(dispatcher->GetDescriptor(), SOL_SOCKET, SO_ERROR, &errcode,
1343 &len);
1344 }
1345
1346 uint32_t ff = 0;
1347
1348 // Check readable descriptors. If we're waiting on an accept, signal
1349 // that. Otherwise we're waiting for data, check to see if we're
1350 // readable or really closed.
1351 // TODO(pthatcher): Only peek at TCP descriptors.
1352 if (readable) {
1353 if (dispatcher->GetRequestedEvents() & DE_ACCEPT) {
1354 ff |= DE_ACCEPT;
1355 } else if (errcode || dispatcher->IsDescriptorClosed()) {
1356 ff |= DE_CLOSE;
1357 } else {
1358 ff |= DE_READ;
1359 }
1360 }
1361
1362 // Check writable descriptors. If we're waiting on a connect, detect
1363 // success versus failure by the reaped error code.
1364 if (writable) {
1365 if (dispatcher->GetRequestedEvents() & DE_CONNECT) {
1366 if (!errcode) {
1367 ff |= DE_CONNECT;
1368 } else {
1369 ff |= DE_CLOSE;
1370 }
1371 } else {
1372 ff |= DE_WRITE;
1373 }
1374 }
1375
1376 // Tell the descriptor about the event.
1377 if (ff != 0) {
1378 dispatcher->OnPreEvent(ff);
1379 dispatcher->OnEvent(ff, errcode);
1380 }
1381}
1382
1383bool PhysicalSocketServer::WaitSelect(int cmsWait, bool process_io) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001384 // Calculate timing information
1385
deadbeef37f5ecf2017-02-27 14:06:41 -08001386 struct timeval* ptvWait = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001387 struct timeval tvWait;
Niels Möller689b5872018-08-29 09:55:44 +02001388 int64_t stop_us;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001389 if (cmsWait != kForever) {
1390 // Calculate wait timeval
1391 tvWait.tv_sec = cmsWait / 1000;
1392 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1393 ptvWait = &tvWait;
1394
Niels Möller689b5872018-08-29 09:55:44 +02001395 // Calculate when to return
1396 stop_us = rtc::TimeMicros() + cmsWait * 1000;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001397 }
1398
1399 // Zero all fd_sets. Don't need to do this inside the loop since
1400 // select() zeros the descriptors not signaled
1401
1402 fd_set fdsRead;
1403 FD_ZERO(&fdsRead);
1404 fd_set fdsWrite;
1405 FD_ZERO(&fdsWrite);
Yves Gerey665174f2018-06-19 15:03:05 +02001406// Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1407// inline assembly in FD_ZERO.
1408// http://crbug.com/344505
pbos@webrtc.org27e58982014-10-07 17:56:53 +00001409#ifdef MEMORY_SANITIZER
1410 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1411 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1412#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001413
1414 fWait_ = true;
1415
1416 while (fWait_) {
1417 int fdmax = -1;
1418 {
1419 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001420 // TODO(jbauch): Support re-entrant waiting.
1421 RTC_DCHECK(!processing_dispatchers_);
1422 for (Dispatcher* pdispatcher : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001423 // Query dispatchers for read and write wait state
nisseede5da42017-01-12 05:15:36 -08001424 RTC_DCHECK(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001425 if (!process_io && (pdispatcher != signal_wakeup_))
1426 continue;
1427 int fd = pdispatcher->GetDescriptor();
jbauchde4db112017-05-31 13:09:18 -07001428 // "select"ing a file descriptor that is equal to or larger than
1429 // FD_SETSIZE will result in undefined behavior.
1430 RTC_DCHECK_LT(fd, FD_SETSIZE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001431 if (fd > fdmax)
1432 fdmax = fd;
1433
Peter Boström0c4e06b2015-10-07 12:23:21 +02001434 uint32_t ff = pdispatcher->GetRequestedEvents();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001435 if (ff & (DE_READ | DE_ACCEPT))
1436 FD_SET(fd, &fdsRead);
1437 if (ff & (DE_WRITE | DE_CONNECT))
1438 FD_SET(fd, &fdsWrite);
1439 }
1440 }
1441
1442 // Wait then call handlers as appropriate
1443 // < 0 means error
1444 // 0 means timeout
1445 // > 0 means count of descriptors ready
deadbeef37f5ecf2017-02-27 14:06:41 -08001446 int n = select(fdmax + 1, &fdsRead, &fdsWrite, nullptr, ptvWait);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001447
1448 // If error, return error.
1449 if (n < 0) {
1450 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001451 RTC_LOG_E(LS_ERROR, EN, errno) << "select";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001452 return false;
1453 }
1454 // Else ignore the error and keep going. If this EINTR was for one of the
1455 // signals managed by this PhysicalSocketServer, the
1456 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1457 // iteration.
1458 } else if (n == 0) {
1459 // If timeout, return success
1460 return true;
1461 } else {
1462 // We have signaled descriptors
1463 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001464 processing_dispatchers_ = true;
1465 for (Dispatcher* pdispatcher : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001466 int fd = pdispatcher->GetDescriptor();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001467
jbauchde4db112017-05-31 13:09:18 -07001468 bool readable = FD_ISSET(fd, &fdsRead);
1469 if (readable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001470 FD_CLR(fd, &fdsRead);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001471 }
1472
jbauchde4db112017-05-31 13:09:18 -07001473 bool writable = FD_ISSET(fd, &fdsWrite);
1474 if (writable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001475 FD_CLR(fd, &fdsWrite);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001476 }
1477
jbauchde4db112017-05-31 13:09:18 -07001478 // The error code can be signaled through reads or writes.
1479 ProcessEvents(pdispatcher, readable, writable, readable || writable);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001480 }
jbauchde4db112017-05-31 13:09:18 -07001481
1482 processing_dispatchers_ = false;
1483 // Process deferred dispatchers that have been added/removed while the
1484 // events were handled above.
1485 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001486 }
1487
1488 // Recalc the time remaining to wait. Doing it here means it doesn't get
1489 // calced twice the first time through the loop
1490 if (ptvWait) {
1491 ptvWait->tv_sec = 0;
1492 ptvWait->tv_usec = 0;
Niels Möller689b5872018-08-29 09:55:44 +02001493 int64_t time_left_us = stop_us - rtc::TimeMicros();
1494 if (time_left_us > 0) {
1495 ptvWait->tv_sec = time_left_us / rtc::kNumMicrosecsPerSec;
1496 ptvWait->tv_usec = time_left_us % rtc::kNumMicrosecsPerSec;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001497 }
1498 }
1499 }
1500
1501 return true;
1502}
1503
jbauchde4db112017-05-31 13:09:18 -07001504#if defined(WEBRTC_USE_EPOLL)
1505
1506// Initial number of events to process with one call to "epoll_wait".
1507static const size_t kInitialEpollEvents = 128;
1508
1509// Maximum number of events to process with one call to "epoll_wait".
1510static const size_t kMaxEpollEvents = 8192;
1511
1512void PhysicalSocketServer::AddEpoll(Dispatcher* pdispatcher) {
1513 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1514 int fd = pdispatcher->GetDescriptor();
1515 RTC_DCHECK(fd != INVALID_SOCKET);
1516 if (fd == INVALID_SOCKET) {
1517 return;
1518 }
1519
1520 struct epoll_event event = {0};
1521 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
1522 event.data.ptr = pdispatcher;
1523 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &event);
1524 RTC_DCHECK_EQ(err, 0);
1525 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001526 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_ADD";
jbauchde4db112017-05-31 13:09:18 -07001527 }
1528}
1529
1530void PhysicalSocketServer::RemoveEpoll(Dispatcher* pdispatcher) {
1531 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1532 int fd = pdispatcher->GetDescriptor();
1533 RTC_DCHECK(fd != INVALID_SOCKET);
1534 if (fd == INVALID_SOCKET) {
1535 return;
1536 }
1537
1538 struct epoll_event event = {0};
1539 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &event);
1540 RTC_DCHECK(err == 0 || errno == ENOENT);
1541 if (err == -1) {
1542 if (errno == ENOENT) {
1543 // Socket has already been closed.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001544 RTC_LOG_E(LS_VERBOSE, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001545 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001546 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001547 }
1548 }
1549}
1550
1551void PhysicalSocketServer::UpdateEpoll(Dispatcher* pdispatcher) {
1552 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1553 int fd = pdispatcher->GetDescriptor();
1554 RTC_DCHECK(fd != INVALID_SOCKET);
1555 if (fd == INVALID_SOCKET) {
1556 return;
1557 }
1558
1559 struct epoll_event event = {0};
1560 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
1561 event.data.ptr = pdispatcher;
1562 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &event);
1563 RTC_DCHECK_EQ(err, 0);
1564 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001565 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_MOD";
jbauchde4db112017-05-31 13:09:18 -07001566 }
1567}
1568
1569bool PhysicalSocketServer::WaitEpoll(int cmsWait) {
1570 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1571 int64_t tvWait = -1;
1572 int64_t tvStop = -1;
1573 if (cmsWait != kForever) {
1574 tvWait = cmsWait;
1575 tvStop = TimeAfter(cmsWait);
1576 }
1577
1578 if (epoll_events_.empty()) {
1579 // The initial space to receive events is created only if epoll is used.
1580 epoll_events_.resize(kInitialEpollEvents);
1581 }
1582
1583 fWait_ = true;
1584
1585 while (fWait_) {
1586 // Wait then call handlers as appropriate
1587 // < 0 means error
1588 // 0 means timeout
1589 // > 0 means count of descriptors ready
1590 int n = epoll_wait(epoll_fd_, &epoll_events_[0],
1591 static_cast<int>(epoll_events_.size()),
1592 static_cast<int>(tvWait));
1593 if (n < 0) {
1594 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001595 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll";
jbauchde4db112017-05-31 13:09:18 -07001596 return false;
1597 }
1598 // Else ignore the error and keep going. If this EINTR was for one of the
1599 // signals managed by this PhysicalSocketServer, the
1600 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1601 // iteration.
1602 } else if (n == 0) {
1603 // If timeout, return success
1604 return true;
1605 } else {
1606 // We have signaled descriptors
1607 CritScope cr(&crit_);
1608 for (int i = 0; i < n; ++i) {
1609 const epoll_event& event = epoll_events_[i];
1610 Dispatcher* pdispatcher = static_cast<Dispatcher*>(event.data.ptr);
1611 if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1612 // The dispatcher for this socket no longer exists.
1613 continue;
1614 }
1615
1616 bool readable = (event.events & (EPOLLIN | EPOLLPRI));
1617 bool writable = (event.events & EPOLLOUT);
1618 bool check_error = (event.events & (EPOLLRDHUP | EPOLLERR | EPOLLHUP));
1619
1620 ProcessEvents(pdispatcher, readable, writable, check_error);
1621 }
1622 }
1623
1624 if (static_cast<size_t>(n) == epoll_events_.size() &&
1625 epoll_events_.size() < kMaxEpollEvents) {
1626 // We used the complete space to receive events, increase size for future
1627 // iterations.
1628 epoll_events_.resize(std::max(epoll_events_.size() * 2, kMaxEpollEvents));
1629 }
1630
1631 if (cmsWait != kForever) {
1632 tvWait = TimeDiff(tvStop, TimeMillis());
1633 if (tvWait < 0) {
1634 // Return success on timeout.
1635 return true;
1636 }
1637 }
1638 }
1639
1640 return true;
1641}
1642
1643bool PhysicalSocketServer::WaitPoll(int cmsWait, Dispatcher* dispatcher) {
1644 RTC_DCHECK(dispatcher);
1645 int64_t tvWait = -1;
1646 int64_t tvStop = -1;
1647 if (cmsWait != kForever) {
1648 tvWait = cmsWait;
1649 tvStop = TimeAfter(cmsWait);
1650 }
1651
1652 fWait_ = true;
1653
1654 struct pollfd fds = {0};
1655 int fd = dispatcher->GetDescriptor();
1656 fds.fd = fd;
1657
1658 while (fWait_) {
1659 uint32_t ff = dispatcher->GetRequestedEvents();
1660 fds.events = 0;
1661 if (ff & (DE_READ | DE_ACCEPT)) {
1662 fds.events |= POLLIN;
1663 }
1664 if (ff & (DE_WRITE | DE_CONNECT)) {
1665 fds.events |= POLLOUT;
1666 }
1667 fds.revents = 0;
1668
1669 // Wait then call handlers as appropriate
1670 // < 0 means error
1671 // 0 means timeout
1672 // > 0 means count of descriptors ready
1673 int n = poll(&fds, 1, static_cast<int>(tvWait));
1674 if (n < 0) {
1675 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001676 RTC_LOG_E(LS_ERROR, EN, errno) << "poll";
jbauchde4db112017-05-31 13:09:18 -07001677 return false;
1678 }
1679 // Else ignore the error and keep going. If this EINTR was for one of the
1680 // signals managed by this PhysicalSocketServer, the
1681 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1682 // iteration.
1683 } else if (n == 0) {
1684 // If timeout, return success
1685 return true;
1686 } else {
1687 // We have signaled descriptors (should only be the passed dispatcher).
1688 RTC_DCHECK_EQ(n, 1);
1689 RTC_DCHECK_EQ(fds.fd, fd);
1690
1691 bool readable = (fds.revents & (POLLIN | POLLPRI));
1692 bool writable = (fds.revents & POLLOUT);
1693 bool check_error = (fds.revents & (POLLRDHUP | POLLERR | POLLHUP));
1694
1695 ProcessEvents(dispatcher, readable, writable, check_error);
1696 }
1697
1698 if (cmsWait != kForever) {
1699 tvWait = TimeDiff(tvStop, TimeMillis());
1700 if (tvWait < 0) {
1701 // Return success on timeout.
1702 return true;
1703 }
1704 }
1705 }
1706
1707 return true;
1708}
1709
1710#endif // WEBRTC_USE_EPOLL
1711
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001712static void GlobalSignalHandler(int signum) {
1713 PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
1714}
1715
1716bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
1717 void (*handler)(int)) {
1718 // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
1719 // otherwise set one.
1720 if (handler == SIG_IGN || handler == SIG_DFL) {
1721 if (!InstallSignal(signum, handler)) {
1722 return false;
1723 }
1724 if (signal_dispatcher_) {
1725 signal_dispatcher_->ClearHandler(signum);
1726 if (!signal_dispatcher_->HasHandlers()) {
1727 signal_dispatcher_.reset();
1728 }
1729 }
1730 } else {
1731 if (!signal_dispatcher_) {
1732 signal_dispatcher_.reset(new PosixSignalDispatcher(this));
1733 }
1734 signal_dispatcher_->SetHandler(signum, handler);
1735 if (!InstallSignal(signum, &GlobalSignalHandler)) {
1736 return false;
1737 }
1738 }
1739 return true;
1740}
1741
1742Dispatcher* PhysicalSocketServer::signal_dispatcher() {
1743 return signal_dispatcher_.get();
1744}
1745
1746bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
1747 struct sigaction act;
1748 // It doesn't really matter what we set this mask to.
1749 if (sigemptyset(&act.sa_mask) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001750 RTC_LOG_ERR(LS_ERROR) << "Couldn't set mask";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001751 return false;
1752 }
1753 act.sa_handler = handler;
1754#if !defined(__native_client__)
1755 // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
1756 // and it's a nuisance. Though some syscalls still return EINTR and there's no
1757 // real standard for which ones. :(
1758 act.sa_flags = SA_RESTART;
1759#else
1760 act.sa_flags = 0;
1761#endif
deadbeef37f5ecf2017-02-27 14:06:41 -08001762 if (sigaction(signum, &act, nullptr) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001763 RTC_LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001764 return false;
1765 }
1766 return true;
1767}
1768#endif // WEBRTC_POSIX
1769
1770#if defined(WEBRTC_WIN)
1771bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
Honghai Zhang82d78622016-05-06 11:29:15 -07001772 int64_t cmsTotal = cmsWait;
1773 int64_t cmsElapsed = 0;
1774 int64_t msStart = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001775
1776 fWait_ = true;
1777 while (fWait_) {
1778 std::vector<WSAEVENT> events;
Yves Gerey665174f2018-06-19 15:03:05 +02001779 std::vector<Dispatcher*> event_owners;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001780
1781 events.push_back(socket_ev_);
1782
1783 {
1784 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001785 // TODO(jbauch): Support re-entrant waiting.
1786 RTC_DCHECK(!processing_dispatchers_);
1787
1788 // Calling "CheckSignalClose" might remove a closed dispatcher from the
1789 // set. This must be deferred to prevent invalidating the iterator.
1790 processing_dispatchers_ = true;
1791 for (Dispatcher* disp : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001792 if (!process_io && (disp != signal_wakeup_))
1793 continue;
1794 SOCKET s = disp->GetSocket();
1795 if (disp->CheckSignalClose()) {
1796 // We just signalled close, don't poll this socket
1797 } else if (s != INVALID_SOCKET) {
Yves Gerey665174f2018-06-19 15:03:05 +02001798 WSAEventSelect(s, events[0],
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001799 FlagsToEvents(disp->GetRequestedEvents()));
1800 } else {
1801 events.push_back(disp->GetWSAEvent());
1802 event_owners.push_back(disp);
1803 }
1804 }
jbauchde4db112017-05-31 13:09:18 -07001805
1806 processing_dispatchers_ = false;
1807 // Process deferred dispatchers that have been added/removed while the
1808 // events were handled above.
1809 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001810 }
1811
1812 // Which is shorter, the delay wait or the asked wait?
1813
Honghai Zhang82d78622016-05-06 11:29:15 -07001814 int64_t cmsNext;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001815 if (cmsWait == kForever) {
1816 cmsNext = cmsWait;
1817 } else {
Honghai Zhang82d78622016-05-06 11:29:15 -07001818 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001819 }
1820
1821 // Wait for one of the events to signal
Yves Gerey665174f2018-06-19 15:03:05 +02001822 DWORD dw =
1823 WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()), &events[0],
1824 false, static_cast<DWORD>(cmsNext), false);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001825
1826 if (dw == WSA_WAIT_FAILED) {
1827 // Failed?
jbauch095ae152015-12-18 01:39:55 -08001828 // TODO(pthatcher): need a better strategy than this!
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001829 WSAGetLastError();
nissec80e7412017-01-11 05:56:46 -08001830 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001831 return false;
1832 } else if (dw == WSA_WAIT_TIMEOUT) {
1833 // Timeout?
1834 return true;
1835 } else {
1836 // Figure out which one it is and call it
1837 CritScope cr(&crit_);
1838 int index = dw - WSA_WAIT_EVENT_0;
1839 if (index > 0) {
Yves Gerey665174f2018-06-19 15:03:05 +02001840 --index; // The first event is the socket event
jbauchde4db112017-05-31 13:09:18 -07001841 Dispatcher* disp = event_owners[index];
1842 // The dispatcher could have been removed while waiting for events.
1843 if (dispatchers_.find(disp) != dispatchers_.end()) {
1844 disp->OnPreEvent(0);
1845 disp->OnEvent(0, 0);
1846 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001847 } else if (process_io) {
jbauchde4db112017-05-31 13:09:18 -07001848 processing_dispatchers_ = true;
1849 for (Dispatcher* disp : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001850 SOCKET s = disp->GetSocket();
1851 if (s == INVALID_SOCKET)
1852 continue;
1853
1854 WSANETWORKEVENTS wsaEvents;
1855 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1856 if (err == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001857 {
1858 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1859 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001860 RTC_LOG(WARNING)
1861 << "PhysicalSocketServer got FD_READ_BIT error "
1862 << wsaEvents.iErrorCode[FD_READ_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001863 }
1864 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1865 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001866 RTC_LOG(WARNING)
1867 << "PhysicalSocketServer got FD_WRITE_BIT error "
1868 << wsaEvents.iErrorCode[FD_WRITE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001869 }
1870 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1871 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001872 RTC_LOG(WARNING)
1873 << "PhysicalSocketServer got FD_CONNECT_BIT error "
1874 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001875 }
1876 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1877 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001878 RTC_LOG(WARNING)
1879 << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1880 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001881 }
1882 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1883 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001884 RTC_LOG(WARNING)
1885 << "PhysicalSocketServer got FD_CLOSE_BIT error "
1886 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001887 }
1888 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001889 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001890 int errcode = 0;
1891 if (wsaEvents.lNetworkEvents & FD_READ)
1892 ff |= DE_READ;
1893 if (wsaEvents.lNetworkEvents & FD_WRITE)
1894 ff |= DE_WRITE;
1895 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1896 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1897 ff |= DE_CONNECT;
1898 } else {
1899 ff |= DE_CLOSE;
1900 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1901 }
1902 }
1903 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1904 ff |= DE_ACCEPT;
1905 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1906 ff |= DE_CLOSE;
1907 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1908 }
1909 if (ff != 0) {
1910 disp->OnPreEvent(ff);
1911 disp->OnEvent(ff, errcode);
1912 }
1913 }
1914 }
jbauchde4db112017-05-31 13:09:18 -07001915
1916 processing_dispatchers_ = false;
1917 // Process deferred dispatchers that have been added/removed while the
1918 // events were handled above.
1919 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001920 }
1921
1922 // Reset the network event until new activity occurs
1923 WSAResetEvent(socket_ev_);
1924 }
1925
1926 // Break?
1927 if (!fWait_)
1928 break;
1929 cmsElapsed = TimeSince(msStart);
1930 if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
Yves Gerey665174f2018-06-19 15:03:05 +02001931 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001932 }
1933 }
1934
1935 // Done
1936 return true;
1937}
honghaizcec0a082016-01-15 14:49:09 -08001938#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001939
1940} // namespace rtc