blob: 4ad2857c00c141ad608d5b8c12cb0082d01cb1ab [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020010#include "rtc_base/physicalsocketserver.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000011
12#if defined(_MSC_VER) && _MSC_VER < 1300
Yves Gerey665174f2018-06-19 15:03:05 +020013#pragma warning(disable : 4786)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000014#endif
15
pbos@webrtc.org27e58982014-10-07 17:56:53 +000016#ifdef MEMORY_SANITIZER
17#include <sanitizer/msan_interface.h>
18#endif
19
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000020#if defined(WEBRTC_POSIX)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000021#include <fcntl.h>
Yves Gerey665174f2018-06-19 15:03:05 +020022#include <string.h>
jbauchde4db112017-05-31 13:09:18 -070023#if defined(WEBRTC_USE_EPOLL)
24// "poll" will be used to wait for the signal dispatcher.
25#include <poll.h>
26#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000027#include <signal.h>
Yves Gerey665174f2018-06-19 15:03:05 +020028#include <sys/ioctl.h>
29#include <sys/select.h>
30#include <sys/time.h>
31#include <unistd.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000032#endif
33
34#if defined(WEBRTC_WIN)
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"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "rtc_base/byteorder.h"
48#include "rtc_base/checks.h"
49#include "rtc_base/logging.h"
50#include "rtc_base/networkmonitor.h"
51#include "rtc_base/nullsocketserver.h"
52#include "rtc_base/timeutils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000053
Patrik Höglunda8005cf2017-12-13 16:05:42 +010054#if defined(WEBRTC_WIN)
55#define LAST_SYSTEM_ERROR (::GetLastError())
56#elif defined(__native_client__) && __native_client__
57#define LAST_SYSTEM_ERROR (0)
58#elif defined(WEBRTC_POSIX)
59#define LAST_SYSTEM_ERROR (errno)
60#endif // WEBRTC_WIN
61
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000062#if defined(WEBRTC_POSIX)
63#include <netinet/tcp.h> // for TCP_NODELAY
Yves Gerey665174f2018-06-19 15:03:05 +020064#define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000065typedef void* SockOptArg;
Stefan Holmer9131efd2016-05-23 18:19:26 +020066
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000067#endif // WEBRTC_POSIX
68
Stefan Holmer3ebb3ef2016-05-23 20:26:11 +020069#if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) && !defined(__native_client__)
70
Stefan Holmer9131efd2016-05-23 18:19:26 +020071int64_t GetSocketRecvTimestamp(int socket) {
72 struct timeval tv_ioctl;
73 int ret = ioctl(socket, SIOCGSTAMP, &tv_ioctl);
74 if (ret != 0)
75 return -1;
76 int64_t timestamp =
77 rtc::kNumMicrosecsPerSec * static_cast<int64_t>(tv_ioctl.tv_sec) +
78 static_cast<int64_t>(tv_ioctl.tv_usec);
79 return timestamp;
80}
81
82#else
83
84int64_t GetSocketRecvTimestamp(int socket) {
85 return -1;
86}
87#endif
88
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000089#if defined(WEBRTC_WIN)
90typedef char* SockOptArg;
91#endif
92
jbauchde4db112017-05-31 13:09:18 -070093#if defined(WEBRTC_USE_EPOLL)
94// POLLRDHUP / EPOLLRDHUP are only defined starting with Linux 2.6.17.
95#if !defined(POLLRDHUP)
96#define POLLRDHUP 0x2000
97#endif
98#if !defined(EPOLLRDHUP)
99#define EPOLLRDHUP 0x2000
100#endif
101#endif
102
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000103namespace rtc {
104
danilchapbebf54c2016-04-28 01:32:48 -0700105std::unique_ptr<SocketServer> SocketServer::CreateDefault() {
106#if defined(__native_client__)
107 return std::unique_ptr<SocketServer>(new rtc::NullSocketServer);
108#else
109 return std::unique_ptr<SocketServer>(new rtc::PhysicalSocketServer);
110#endif
111}
112
jbauch095ae152015-12-18 01:39:55 -0800113PhysicalSocket::PhysicalSocket(PhysicalSocketServer* ss, SOCKET s)
Yves Gerey665174f2018-06-19 15:03:05 +0200114 : ss_(ss),
115 s_(s),
116 error_(0),
117 state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED),
118 resolver_(nullptr) {
jbauch095ae152015-12-18 01:39:55 -0800119 if (s_ != INVALID_SOCKET) {
jbauch577f5dc2017-05-17 16:32:26 -0700120 SetEnabledEvents(DE_READ | DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000121
jbauch095ae152015-12-18 01:39:55 -0800122 int type = SOCK_STREAM;
123 socklen_t len = sizeof(type);
nissec16fa5e2017-02-07 07:18:43 -0800124 const int res =
125 getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len);
126 RTC_DCHECK_EQ(0, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000127 udp_ = (SOCK_DGRAM == type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000128 }
jbauch095ae152015-12-18 01:39:55 -0800129}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000130
jbauch095ae152015-12-18 01:39:55 -0800131PhysicalSocket::~PhysicalSocket() {
132 Close();
133}
134
135bool PhysicalSocket::Create(int family, int type) {
136 Close();
137 s_ = ::socket(family, type, 0);
138 udp_ = (SOCK_DGRAM == type);
139 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700140 if (udp_) {
141 SetEnabledEvents(DE_READ | DE_WRITE);
142 }
jbauch095ae152015-12-18 01:39:55 -0800143 return s_ != INVALID_SOCKET;
144}
145
146SocketAddress PhysicalSocket::GetLocalAddress() const {
147 sockaddr_storage addr_storage = {0};
148 socklen_t addrlen = sizeof(addr_storage);
149 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
150 int result = ::getsockname(s_, addr, &addrlen);
151 SocketAddress address;
152 if (result >= 0) {
153 SocketAddressFromSockAddrStorage(addr_storage, &address);
154 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100155 RTC_LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
156 << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000157 }
jbauch095ae152015-12-18 01:39:55 -0800158 return address;
159}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000160
jbauch095ae152015-12-18 01:39:55 -0800161SocketAddress PhysicalSocket::GetRemoteAddress() const {
162 sockaddr_storage addr_storage = {0};
163 socklen_t addrlen = sizeof(addr_storage);
164 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
165 int result = ::getpeername(s_, addr, &addrlen);
166 SocketAddress address;
167 if (result >= 0) {
168 SocketAddressFromSockAddrStorage(addr_storage, &address);
169 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100170 RTC_LOG(LS_WARNING)
171 << "GetRemoteAddress: unable to get remote addr, socket=" << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000172 }
jbauch095ae152015-12-18 01:39:55 -0800173 return address;
174}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000175
jbauch095ae152015-12-18 01:39:55 -0800176int PhysicalSocket::Bind(const SocketAddress& bind_addr) {
deadbeefc874d122017-02-13 15:41:59 -0800177 SocketAddress copied_bind_addr = bind_addr;
178 // If a network binder is available, use it to bind a socket to an interface
179 // instead of bind(), since this is more reliable on an OS with a weak host
180 // model.
deadbeef9ffa13f2017-02-21 16:18:00 -0800181 if (ss_->network_binder() && !bind_addr.IsAnyIP()) {
deadbeefc874d122017-02-13 15:41:59 -0800182 NetworkBindingResult result =
183 ss_->network_binder()->BindSocketToNetwork(s_, bind_addr.ipaddr());
184 if (result == NetworkBindingResult::SUCCESS) {
185 // Since the network binder handled binding the socket to the desired
186 // network interface, we don't need to (and shouldn't) include an IP in
187 // the bind() call; bind() just needs to assign a port.
188 copied_bind_addr.SetIP(GetAnyIP(copied_bind_addr.ipaddr().family()));
189 } else if (result == NetworkBindingResult::NOT_IMPLEMENTED) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100190 RTC_LOG(LS_INFO) << "Can't bind socket to network because "
191 "network binding is not implemented for this OS.";
deadbeefc874d122017-02-13 15:41:59 -0800192 } else {
193 if (bind_addr.IsLoopbackIP()) {
194 // If we couldn't bind to a loopback IP (which should only happen in
195 // test scenarios), continue on. This may be expected behavior.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100196 RTC_LOG(LS_VERBOSE) << "Binding socket to loopback address "
197 << bind_addr.ipaddr().ToString()
198 << " failed; result: " << static_cast<int>(result);
deadbeefc874d122017-02-13 15:41:59 -0800199 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100200 RTC_LOG(LS_WARNING) << "Binding socket to network address "
201 << bind_addr.ipaddr().ToString()
202 << " failed; result: " << static_cast<int>(result);
deadbeefc874d122017-02-13 15:41:59 -0800203 // If a network binding was attempted and failed, we should stop here
204 // and not try to use the socket. Otherwise, we may end up sending
205 // packets with an invalid source address.
206 // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=7026
207 return -1;
208 }
209 }
210 }
jbauch095ae152015-12-18 01:39:55 -0800211 sockaddr_storage addr_storage;
deadbeefc874d122017-02-13 15:41:59 -0800212 size_t len = copied_bind_addr.ToSockAddrStorage(&addr_storage);
jbauch095ae152015-12-18 01:39:55 -0800213 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
214 int err = ::bind(s_, addr, static_cast<int>(len));
215 UpdateLastError();
tfarinaa41ab932015-10-30 16:08:48 -0700216#if !defined(NDEBUG)
jbauch095ae152015-12-18 01:39:55 -0800217 if (0 == err) {
218 dbg_addr_ = "Bound @ ";
219 dbg_addr_.append(GetLocalAddress().ToString());
220 }
tfarinaa41ab932015-10-30 16:08:48 -0700221#endif
jbauch095ae152015-12-18 01:39:55 -0800222 return err;
223}
224
225int PhysicalSocket::Connect(const SocketAddress& addr) {
226 // TODO(pthatcher): Implicit creation is required to reconnect...
227 // ...but should we make it more explicit?
228 if (state_ != CS_CLOSED) {
229 SetError(EALREADY);
230 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000231 }
jbauch095ae152015-12-18 01:39:55 -0800232 if (addr.IsUnresolvedIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100233 RTC_LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
jbauch095ae152015-12-18 01:39:55 -0800234 resolver_ = new AsyncResolver();
235 resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult);
236 resolver_->Start(addr);
237 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000238 return 0;
239 }
240
jbauch095ae152015-12-18 01:39:55 -0800241 return DoConnect(addr);
242}
243
244int PhysicalSocket::DoConnect(const SocketAddress& connect_addr) {
Yves Gerey665174f2018-06-19 15:03:05 +0200245 if ((s_ == INVALID_SOCKET) && !Create(connect_addr.family(), SOCK_STREAM)) {
jbauch095ae152015-12-18 01:39:55 -0800246 return SOCKET_ERROR;
247 }
248 sockaddr_storage addr_storage;
249 size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
250 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
251 int err = ::connect(s_, addr, static_cast<int>(len));
252 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700253 uint8_t events = DE_READ | DE_WRITE;
jbauch095ae152015-12-18 01:39:55 -0800254 if (err == 0) {
255 state_ = CS_CONNECTED;
256 } else if (IsBlockingError(GetError())) {
257 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700258 events |= DE_CONNECT;
jbauch095ae152015-12-18 01:39:55 -0800259 } else {
260 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000261 }
262
jbauch577f5dc2017-05-17 16:32:26 -0700263 EnableEvents(events);
jbauch095ae152015-12-18 01:39:55 -0800264 return 0;
265}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000266
jbauch095ae152015-12-18 01:39:55 -0800267int PhysicalSocket::GetError() const {
268 CritScope cs(&crit_);
269 return error_;
270}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000271
jbauch095ae152015-12-18 01:39:55 -0800272void PhysicalSocket::SetError(int error) {
273 CritScope cs(&crit_);
274 error_ = error;
275}
276
277AsyncSocket::ConnState PhysicalSocket::GetState() const {
278 return state_;
279}
280
281int PhysicalSocket::GetOption(Option opt, int* value) {
282 int slevel;
283 int sopt;
284 if (TranslateOption(opt, &slevel, &sopt) == -1)
285 return -1;
286 socklen_t optlen = sizeof(*value);
287 int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
288 if (ret != -1 && opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000289#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800290 *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000291#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000292 }
jbauch095ae152015-12-18 01:39:55 -0800293 return ret;
294}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000295
jbauch095ae152015-12-18 01:39:55 -0800296int PhysicalSocket::SetOption(Option opt, int value) {
297 int slevel;
298 int sopt;
299 if (TranslateOption(opt, &slevel, &sopt) == -1)
300 return -1;
301 if (opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000302#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800303 value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000304#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000305 }
jbauch095ae152015-12-18 01:39:55 -0800306 return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
307}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000308
jbauch095ae152015-12-18 01:39:55 -0800309int PhysicalSocket::Send(const void* pv, size_t cb) {
Yves Gerey665174f2018-06-19 15:03:05 +0200310 int sent = DoSend(
311 s_, reinterpret_cast<const char*>(pv), static_cast<int>(cb),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000312#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800313 // Suppress SIGPIPE. Without this, attempting to send on a socket whose
314 // other end is closed will result in a SIGPIPE signal being raised to
315 // our process, which by default will terminate the process, which we
316 // don't want. By specifying this flag, we'll just get the error EPIPE
317 // instead and can handle the error gracefully.
318 MSG_NOSIGNAL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000319#else
jbauch095ae152015-12-18 01:39:55 -0800320 0
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000321#endif
jbauch095ae152015-12-18 01:39:55 -0800322 );
323 UpdateLastError();
324 MaybeRemapSendError();
325 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800326 RTC_DCHECK(sent <= static_cast<int>(cb));
jbauchf2a2bf42016-02-03 16:45:32 -0800327 if ((sent > 0 && sent < static_cast<int>(cb)) ||
328 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700329 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000330 }
jbauch095ae152015-12-18 01:39:55 -0800331 return sent;
332}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000333
jbauch095ae152015-12-18 01:39:55 -0800334int PhysicalSocket::SendTo(const void* buffer,
335 size_t length,
336 const SocketAddress& addr) {
337 sockaddr_storage saddr;
338 size_t len = addr.ToSockAddrStorage(&saddr);
Yves Gerey665174f2018-06-19 15:03:05 +0200339 int sent =
340 DoSendTo(s_, static_cast<const char*>(buffer), static_cast<int>(length),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000341#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
Yves Gerey665174f2018-06-19 15:03:05 +0200342 // Suppress SIGPIPE. See above for explanation.
343 MSG_NOSIGNAL,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000344#else
Yves Gerey665174f2018-06-19 15:03:05 +0200345 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000346#endif
Yves Gerey665174f2018-06-19 15:03:05 +0200347 reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
jbauch095ae152015-12-18 01:39:55 -0800348 UpdateLastError();
349 MaybeRemapSendError();
350 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800351 RTC_DCHECK(sent <= static_cast<int>(length));
jbauchf2a2bf42016-02-03 16:45:32 -0800352 if ((sent > 0 && sent < static_cast<int>(length)) ||
353 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700354 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000355 }
jbauch095ae152015-12-18 01:39:55 -0800356 return sent;
357}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000358
Stefan Holmer9131efd2016-05-23 18:19:26 +0200359int PhysicalSocket::Recv(void* buffer, size_t length, int64_t* timestamp) {
Yves Gerey665174f2018-06-19 15:03:05 +0200360 int received =
361 ::recv(s_, static_cast<char*>(buffer), static_cast<int>(length), 0);
jbauch095ae152015-12-18 01:39:55 -0800362 if ((received == 0) && (length != 0)) {
363 // Note: on graceful shutdown, recv can return 0. In this case, we
364 // pretend it is blocking, and then signal close, so that simplifying
365 // assumptions can be made about Recv.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100366 RTC_LOG(LS_WARNING) << "EOF from socket; deferring close event";
jbauch095ae152015-12-18 01:39:55 -0800367 // Must turn this back on so that the select() loop will notice the close
368 // event.
jbauch577f5dc2017-05-17 16:32:26 -0700369 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800370 SetError(EWOULDBLOCK);
371 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000372 }
Stefan Holmer9131efd2016-05-23 18:19:26 +0200373 if (timestamp) {
374 *timestamp = GetSocketRecvTimestamp(s_);
375 }
jbauch095ae152015-12-18 01:39:55 -0800376 UpdateLastError();
377 int error = GetError();
378 bool success = (received >= 0) || IsBlockingError(error);
379 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700380 EnableEvents(DE_READ);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000381 }
jbauch095ae152015-12-18 01:39:55 -0800382 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100383 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000384 }
jbauch095ae152015-12-18 01:39:55 -0800385 return received;
386}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000387
jbauch095ae152015-12-18 01:39:55 -0800388int PhysicalSocket::RecvFrom(void* buffer,
389 size_t length,
Stefan Holmer9131efd2016-05-23 18:19:26 +0200390 SocketAddress* out_addr,
391 int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800392 sockaddr_storage addr_storage;
393 socklen_t addr_len = sizeof(addr_storage);
394 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
395 int received = ::recvfrom(s_, static_cast<char*>(buffer),
396 static_cast<int>(length), 0, addr, &addr_len);
Stefan Holmer9131efd2016-05-23 18:19:26 +0200397 if (timestamp) {
398 *timestamp = GetSocketRecvTimestamp(s_);
399 }
jbauch095ae152015-12-18 01:39:55 -0800400 UpdateLastError();
401 if ((received >= 0) && (out_addr != nullptr))
402 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
403 int error = GetError();
404 bool success = (received >= 0) || IsBlockingError(error);
405 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700406 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800407 }
408 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100409 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
jbauch095ae152015-12-18 01:39:55 -0800410 }
411 return received;
412}
413
414int PhysicalSocket::Listen(int backlog) {
415 int err = ::listen(s_, backlog);
416 UpdateLastError();
417 if (err == 0) {
418 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700419 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800420#if !defined(NDEBUG)
421 dbg_addr_ = "Listening @ ";
422 dbg_addr_.append(GetLocalAddress().ToString());
423#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000424 }
jbauch095ae152015-12-18 01:39:55 -0800425 return err;
426}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000427
jbauch095ae152015-12-18 01:39:55 -0800428AsyncSocket* PhysicalSocket::Accept(SocketAddress* out_addr) {
429 // Always re-subscribe DE_ACCEPT to make sure new incoming connections will
430 // trigger an event even if DoAccept returns an error here.
jbauch577f5dc2017-05-17 16:32:26 -0700431 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800432 sockaddr_storage addr_storage;
433 socklen_t addr_len = sizeof(addr_storage);
434 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
435 SOCKET s = DoAccept(s_, addr, &addr_len);
436 UpdateLastError();
437 if (s == INVALID_SOCKET)
438 return nullptr;
439 if (out_addr != nullptr)
440 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
441 return ss_->WrapSocket(s);
442}
443
444int PhysicalSocket::Close() {
445 if (s_ == INVALID_SOCKET)
446 return 0;
447 int err = ::closesocket(s_);
448 UpdateLastError();
449 s_ = INVALID_SOCKET;
450 state_ = CS_CLOSED;
jbauch577f5dc2017-05-17 16:32:26 -0700451 SetEnabledEvents(0);
jbauch095ae152015-12-18 01:39:55 -0800452 if (resolver_) {
453 resolver_->Destroy(false);
454 resolver_ = nullptr;
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 -0800459SOCKET PhysicalSocket::DoAccept(SOCKET socket,
460 sockaddr* addr,
461 socklen_t* addrlen) {
462 return ::accept(socket, addr, addrlen);
463}
464
jbauchf2a2bf42016-02-03 16:45:32 -0800465int PhysicalSocket::DoSend(SOCKET socket, const char* buf, int len, int flags) {
466 return ::send(socket, buf, len, flags);
467}
468
469int PhysicalSocket::DoSendTo(SOCKET socket,
470 const char* buf,
471 int len,
472 int flags,
473 const struct sockaddr* dest_addr,
474 socklen_t addrlen) {
475 return ::sendto(socket, buf, len, flags, dest_addr, addrlen);
476}
477
jbauch095ae152015-12-18 01:39:55 -0800478void PhysicalSocket::OnResolveResult(AsyncResolverInterface* resolver) {
479 if (resolver != resolver_) {
480 return;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000481 }
482
jbauch095ae152015-12-18 01:39:55 -0800483 int error = resolver_->GetError();
484 if (error == 0) {
485 error = DoConnect(resolver_->address());
486 } else {
487 Close();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000488 }
489
jbauch095ae152015-12-18 01:39:55 -0800490 if (error) {
491 SetError(error);
492 SignalCloseEvent(this, error);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000493 }
jbauch095ae152015-12-18 01:39:55 -0800494}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000495
jbauch095ae152015-12-18 01:39:55 -0800496void PhysicalSocket::UpdateLastError() {
Patrik Höglunda8005cf2017-12-13 16:05:42 +0100497 SetError(LAST_SYSTEM_ERROR);
jbauch095ae152015-12-18 01:39:55 -0800498}
499
500void PhysicalSocket::MaybeRemapSendError() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000501#if defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800502 // https://developer.apple.com/library/mac/documentation/Darwin/
503 // Reference/ManPages/man2/sendto.2.html
504 // ENOBUFS - The output queue for a network interface is full.
505 // This generally indicates that the interface has stopped sending,
506 // but may be caused by transient congestion.
507 if (GetError() == ENOBUFS) {
508 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000509 }
jbauch095ae152015-12-18 01:39:55 -0800510#endif
511}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000512
jbauch577f5dc2017-05-17 16:32:26 -0700513void PhysicalSocket::SetEnabledEvents(uint8_t events) {
514 enabled_events_ = events;
515}
516
517void PhysicalSocket::EnableEvents(uint8_t events) {
518 enabled_events_ |= events;
519}
520
521void PhysicalSocket::DisableEvents(uint8_t events) {
522 enabled_events_ &= ~events;
523}
524
jbauch095ae152015-12-18 01:39:55 -0800525int PhysicalSocket::TranslateOption(Option opt, int* slevel, int* sopt) {
526 switch (opt) {
527 case OPT_DONTFRAGMENT:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000528#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800529 *slevel = IPPROTO_IP;
530 *sopt = IP_DONTFRAGMENT;
531 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000532#elif defined(WEBRTC_MAC) || defined(BSD) || defined(__native_client__)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100533 RTC_LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
jbauch095ae152015-12-18 01:39:55 -0800534 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000535#elif defined(WEBRTC_POSIX)
jbauch095ae152015-12-18 01:39:55 -0800536 *slevel = IPPROTO_IP;
537 *sopt = IP_MTU_DISCOVER;
538 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000539#endif
jbauch095ae152015-12-18 01:39:55 -0800540 case OPT_RCVBUF:
541 *slevel = SOL_SOCKET;
542 *sopt = SO_RCVBUF;
543 break;
544 case OPT_SNDBUF:
545 *slevel = SOL_SOCKET;
546 *sopt = SO_SNDBUF;
547 break;
548 case OPT_NODELAY:
549 *slevel = IPPROTO_TCP;
550 *sopt = TCP_NODELAY;
551 break;
552 case OPT_DSCP:
Mirko Bonadei675513b2017-11-09 11:09:25 +0100553 RTC_LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
jbauch095ae152015-12-18 01:39:55 -0800554 return -1;
555 case OPT_RTP_SENDTIME_EXTN_ID:
556 return -1; // No logging is necessary as this not a OS socket option.
557 default:
nissec80e7412017-01-11 05:56:46 -0800558 RTC_NOTREACHED();
jbauch095ae152015-12-18 01:39:55 -0800559 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000560 }
jbauch095ae152015-12-18 01:39:55 -0800561 return 0;
562}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000563
Yves Gerey665174f2018-06-19 15:03:05 +0200564SocketDispatcher::SocketDispatcher(PhysicalSocketServer* ss)
jbauch4331fcd2016-01-06 22:20:28 -0800565#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200566 : PhysicalSocket(ss),
567 id_(0),
568 signal_close_(false)
jbauch4331fcd2016-01-06 22:20:28 -0800569#else
Yves Gerey665174f2018-06-19 15:03:05 +0200570 : PhysicalSocket(ss)
jbauch4331fcd2016-01-06 22:20:28 -0800571#endif
572{
573}
574
Yves Gerey665174f2018-06-19 15:03:05 +0200575SocketDispatcher::SocketDispatcher(SOCKET s, PhysicalSocketServer* ss)
jbauch4331fcd2016-01-06 22:20:28 -0800576#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200577 : PhysicalSocket(ss, s),
578 id_(0),
579 signal_close_(false)
jbauch4331fcd2016-01-06 22:20:28 -0800580#else
Yves Gerey665174f2018-06-19 15:03:05 +0200581 : PhysicalSocket(ss, s)
jbauch4331fcd2016-01-06 22:20:28 -0800582#endif
583{
584}
585
586SocketDispatcher::~SocketDispatcher() {
587 Close();
588}
589
590bool SocketDispatcher::Initialize() {
nisseede5da42017-01-12 05:15:36 -0800591 RTC_DCHECK(s_ != INVALID_SOCKET);
Yves Gerey665174f2018-06-19 15:03:05 +0200592// Must be a non-blocking
jbauch4331fcd2016-01-06 22:20:28 -0800593#if defined(WEBRTC_WIN)
594 u_long argp = 1;
595 ioctlsocket(s_, FIONBIO, &argp);
596#elif defined(WEBRTC_POSIX)
597 fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
598#endif
deadbeefeae45642017-05-26 16:27:09 -0700599#if defined(WEBRTC_IOS)
600 // iOS may kill sockets when the app is moved to the background
601 // (specifically, if the app doesn't use the "voip" UIBackgroundMode). When
602 // we attempt to write to such a socket, SIGPIPE will be raised, which by
603 // default will terminate the process, which we don't want. By specifying
604 // this socket option, SIGPIPE will be disabled for the socket.
605 int value = 1;
606 ::setsockopt(s_, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value));
607#endif
jbauch4331fcd2016-01-06 22:20:28 -0800608 ss_->Add(this);
609 return true;
610}
611
612bool SocketDispatcher::Create(int type) {
613 return Create(AF_INET, type);
614}
615
616bool SocketDispatcher::Create(int family, int type) {
617 // Change the socket to be non-blocking.
618 if (!PhysicalSocket::Create(family, type))
619 return false;
620
621 if (!Initialize())
622 return false;
623
624#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200625 do {
626 id_ = ++next_id_;
627 } while (id_ == 0);
jbauch4331fcd2016-01-06 22:20:28 -0800628#endif
629 return true;
630}
631
632#if defined(WEBRTC_WIN)
633
634WSAEVENT SocketDispatcher::GetWSAEvent() {
635 return WSA_INVALID_EVENT;
636}
637
638SOCKET SocketDispatcher::GetSocket() {
639 return s_;
640}
641
642bool SocketDispatcher::CheckSignalClose() {
643 if (!signal_close_)
644 return false;
645
646 char ch;
647 if (recv(s_, &ch, 1, MSG_PEEK) > 0)
648 return false;
649
650 state_ = CS_CLOSED;
651 signal_close_ = false;
652 SignalCloseEvent(this, signal_err_);
653 return true;
654}
655
656int SocketDispatcher::next_id_ = 0;
657
658#elif defined(WEBRTC_POSIX)
659
660int SocketDispatcher::GetDescriptor() {
661 return s_;
662}
663
664bool SocketDispatcher::IsDescriptorClosed() {
deadbeeffaedf7f2017-02-09 15:09:22 -0800665 if (udp_) {
666 // The MSG_PEEK trick doesn't work for UDP, since (at least in some
667 // circumstances) it requires reading an entire UDP packet, which would be
668 // bad for performance here. So, just check whether |s_| has been closed,
669 // which should be sufficient.
670 return s_ == INVALID_SOCKET;
671 }
jbauch4331fcd2016-01-06 22:20:28 -0800672 // We don't have a reliable way of distinguishing end-of-stream
673 // from readability. So test on each readable call. Is this
674 // inefficient? Probably.
675 char ch;
676 ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
677 if (res > 0) {
678 // Data available, so not closed.
679 return false;
680 } else if (res == 0) {
681 // EOF, so closed.
682 return true;
683 } else { // error
684 switch (errno) {
685 // Returned if we've already closed s_.
686 case EBADF:
687 // Returned during ungraceful peer shutdown.
688 case ECONNRESET:
689 return true;
deadbeeffaedf7f2017-02-09 15:09:22 -0800690 // The normal blocking error; don't log anything.
691 case EWOULDBLOCK:
692 // Interrupted system call.
693 case EINTR:
694 return false;
jbauch4331fcd2016-01-06 22:20:28 -0800695 default:
696 // Assume that all other errors are just blocking errors, meaning the
697 // connection is still good but we just can't read from it right now.
698 // This should only happen when connecting (and at most once), because
699 // in all other cases this function is only called if the file
700 // descriptor is already known to be in the readable state. However,
701 // it's not necessary a problem if we spuriously interpret a
702 // "connection lost"-type error as a blocking error, because typically
703 // the next recv() will get EOF, so we'll still eventually notice that
704 // the socket is closed.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100705 RTC_LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
jbauch4331fcd2016-01-06 22:20:28 -0800706 return false;
707 }
708 }
709}
710
Yves Gerey665174f2018-06-19 15:03:05 +0200711#endif // WEBRTC_POSIX
jbauch4331fcd2016-01-06 22:20:28 -0800712
713uint32_t SocketDispatcher::GetRequestedEvents() {
jbauch577f5dc2017-05-17 16:32:26 -0700714 return enabled_events();
jbauch4331fcd2016-01-06 22:20:28 -0800715}
716
717void SocketDispatcher::OnPreEvent(uint32_t ff) {
718 if ((ff & DE_CONNECT) != 0)
719 state_ = CS_CONNECTED;
720
721#if defined(WEBRTC_WIN)
Yves Gerey665174f2018-06-19 15:03:05 +0200722// We set CS_CLOSED from CheckSignalClose.
jbauch4331fcd2016-01-06 22:20:28 -0800723#elif defined(WEBRTC_POSIX)
724 if ((ff & DE_CLOSE) != 0)
725 state_ = CS_CLOSED;
726#endif
727}
728
729#if defined(WEBRTC_WIN)
730
731void SocketDispatcher::OnEvent(uint32_t ff, int err) {
732 int cache_id = id_;
733 // Make sure we deliver connect/accept first. Otherwise, consumers may see
734 // something like a READ followed by a CONNECT, which would be odd.
735 if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
736 if (ff != DE_CONNECT)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100737 RTC_LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
jbauch577f5dc2017-05-17 16:32:26 -0700738 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800739#if !defined(NDEBUG)
740 dbg_addr_ = "Connected @ ";
741 dbg_addr_.append(GetRemoteAddress().ToString());
742#endif
743 SignalConnectEvent(this);
744 }
745 if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700746 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800747 SignalReadEvent(this);
748 }
749 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700750 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800751 SignalReadEvent(this);
752 }
753 if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700754 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800755 SignalWriteEvent(this);
756 }
757 if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
758 signal_close_ = true;
759 signal_err_ = err;
760 }
761}
762
763#elif defined(WEBRTC_POSIX)
764
765void SocketDispatcher::OnEvent(uint32_t ff, int err) {
jbauchde4db112017-05-31 13:09:18 -0700766#if defined(WEBRTC_USE_EPOLL)
767 // Remember currently enabled events so we can combine multiple changes
768 // into one update call later.
769 // The signal handlers might re-enable events disabled here, so we can't
770 // keep a list of events to disable at the end of the method. This list
771 // would not be updated with the events enabled by the signal handlers.
772 StartBatchedEventUpdates();
773#endif
jbauch4331fcd2016-01-06 22:20:28 -0800774 // Make sure we deliver connect/accept first. Otherwise, consumers may see
775 // something like a READ followed by a CONNECT, which would be odd.
776 if ((ff & DE_CONNECT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700777 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800778 SignalConnectEvent(this);
779 }
780 if ((ff & DE_ACCEPT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700781 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800782 SignalReadEvent(this);
783 }
784 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700785 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800786 SignalReadEvent(this);
787 }
788 if ((ff & DE_WRITE) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700789 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800790 SignalWriteEvent(this);
791 }
792 if ((ff & DE_CLOSE) != 0) {
793 // The socket is now dead to us, so stop checking it.
jbauch577f5dc2017-05-17 16:32:26 -0700794 SetEnabledEvents(0);
jbauch4331fcd2016-01-06 22:20:28 -0800795 SignalCloseEvent(this, err);
796 }
jbauchde4db112017-05-31 13:09:18 -0700797#if defined(WEBRTC_USE_EPOLL)
798 FinishBatchedEventUpdates();
799#endif
jbauch4331fcd2016-01-06 22:20:28 -0800800}
801
Yves Gerey665174f2018-06-19 15:03:05 +0200802#endif // WEBRTC_POSIX
jbauch4331fcd2016-01-06 22:20:28 -0800803
jbauchde4db112017-05-31 13:09:18 -0700804#if defined(WEBRTC_USE_EPOLL)
805
806static int GetEpollEvents(uint32_t ff) {
807 int events = 0;
808 if (ff & (DE_READ | DE_ACCEPT)) {
809 events |= EPOLLIN;
810 }
811 if (ff & (DE_WRITE | DE_CONNECT)) {
812 events |= EPOLLOUT;
813 }
814 return events;
815}
816
817void SocketDispatcher::StartBatchedEventUpdates() {
818 RTC_DCHECK_EQ(saved_enabled_events_, -1);
819 saved_enabled_events_ = enabled_events();
820}
821
822void SocketDispatcher::FinishBatchedEventUpdates() {
823 RTC_DCHECK_NE(saved_enabled_events_, -1);
824 uint8_t old_events = static_cast<uint8_t>(saved_enabled_events_);
825 saved_enabled_events_ = -1;
826 MaybeUpdateDispatcher(old_events);
827}
828
829void SocketDispatcher::MaybeUpdateDispatcher(uint8_t old_events) {
830 if (GetEpollEvents(enabled_events()) != GetEpollEvents(old_events) &&
831 saved_enabled_events_ == -1) {
832 ss_->Update(this);
833 }
834}
835
836void SocketDispatcher::SetEnabledEvents(uint8_t events) {
837 uint8_t old_events = enabled_events();
838 PhysicalSocket::SetEnabledEvents(events);
839 MaybeUpdateDispatcher(old_events);
840}
841
842void SocketDispatcher::EnableEvents(uint8_t events) {
843 uint8_t old_events = enabled_events();
844 PhysicalSocket::EnableEvents(events);
845 MaybeUpdateDispatcher(old_events);
846}
847
848void SocketDispatcher::DisableEvents(uint8_t events) {
849 uint8_t old_events = enabled_events();
850 PhysicalSocket::DisableEvents(events);
851 MaybeUpdateDispatcher(old_events);
852}
853
854#endif // WEBRTC_USE_EPOLL
855
jbauch4331fcd2016-01-06 22:20:28 -0800856int SocketDispatcher::Close() {
857 if (s_ == INVALID_SOCKET)
858 return 0;
859
860#if defined(WEBRTC_WIN)
861 id_ = 0;
862 signal_close_ = false;
863#endif
864 ss_->Remove(this);
865 return PhysicalSocket::Close();
866}
867
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000868#if defined(WEBRTC_POSIX)
869class EventDispatcher : public Dispatcher {
870 public:
871 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
872 if (pipe(afd_) < 0)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100873 RTC_LOG(LERROR) << "pipe failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000874 ss_->Add(this);
875 }
876
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000877 ~EventDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000878 ss_->Remove(this);
879 close(afd_[0]);
880 close(afd_[1]);
881 }
882
883 virtual void Signal() {
884 CritScope cs(&crit_);
885 if (!fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200886 const uint8_t b[1] = {0};
nissec16fa5e2017-02-07 07:18:43 -0800887 const ssize_t res = write(afd_[1], b, sizeof(b));
888 RTC_DCHECK_EQ(1, res);
889 fSignaled_ = true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000890 }
891 }
892
Peter Boström0c4e06b2015-10-07 12:23:21 +0200893 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000894
Peter Boström0c4e06b2015-10-07 12:23:21 +0200895 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000896 // It is not possible to perfectly emulate an auto-resetting event with
897 // pipes. This simulates it by resetting before the event is handled.
898
899 CritScope cs(&crit_);
900 if (fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200901 uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
nissec16fa5e2017-02-07 07:18:43 -0800902 const ssize_t res = read(afd_[0], b, sizeof(b));
903 RTC_DCHECK_EQ(1, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000904 fSignaled_ = false;
905 }
906 }
907
nissec80e7412017-01-11 05:56:46 -0800908 void OnEvent(uint32_t ff, int err) override { RTC_NOTREACHED(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000909
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000910 int GetDescriptor() override { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000911
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000912 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000913
914 private:
Yves Gerey665174f2018-06-19 15:03:05 +0200915 PhysicalSocketServer* ss_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000916 int afd_[2];
917 bool fSignaled_;
918 CriticalSection crit_;
919};
920
921// These two classes use the self-pipe trick to deliver POSIX signals to our
922// select loop. This is the only safe, reliable, cross-platform way to do
923// non-trivial things with a POSIX signal in an event-driven program (until
924// proper pselect() implementations become ubiquitous).
925
926class PosixSignalHandler {
927 public:
928 // POSIX only specifies 32 signals, but in principle the system might have
929 // more and the programmer might choose to use them, so we size our array
930 // for 128.
931 static const int kNumPosixSignals = 128;
932
933 // There is just a single global instance. (Signal handlers do not get any
934 // sort of user-defined void * parameter, so they can't access anything that
935 // isn't global.)
936 static PosixSignalHandler* Instance() {
Niels Möller14682a32018-05-24 08:54:25 +0200937 static PosixSignalHandler* const instance = new PosixSignalHandler();
938 return instance;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000939 }
940
941 // Returns true if the given signal number is set.
942 bool IsSignalSet(int signum) const {
nisseede5da42017-01-12 05:15:36 -0800943 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800944 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000945 return received_signal_[signum];
946 } else {
947 return false;
948 }
949 }
950
951 // Clears the given signal number.
952 void ClearSignal(int signum) {
nisseede5da42017-01-12 05:15:36 -0800953 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800954 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000955 received_signal_[signum] = false;
956 }
957 }
958
959 // Returns the file descriptor to monitor for signal events.
Yves Gerey665174f2018-06-19 15:03:05 +0200960 int GetDescriptor() const { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000961
962 // This is called directly from our real signal handler, so it must be
963 // signal-handler-safe. That means it cannot assume anything about the
964 // user-level state of the process, since the handler could be executed at any
965 // time on any thread.
966 void OnPosixSignalReceived(int signum) {
tfarina5237aaf2015-11-10 23:44:30 -0800967 if (signum >= static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000968 // We don't have space in our array for this.
969 return;
970 }
971 // Set a flag saying we've seen this signal.
972 received_signal_[signum] = true;
973 // Notify application code that we got a signal.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200974 const uint8_t b[1] = {0};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000975 if (-1 == write(afd_[1], b, sizeof(b))) {
976 // Nothing we can do here. If there's an error somehow then there's
977 // nothing we can safely do from a signal handler.
978 // No, we can't even safely log it.
979 // But, we still have to check the return value here. Otherwise,
980 // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
981 return;
982 }
983 }
984
985 private:
986 PosixSignalHandler() {
987 if (pipe(afd_) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100988 RTC_LOG_ERR(LS_ERROR) << "pipe failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000989 return;
990 }
991 if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100992 RTC_LOG_ERR(LS_WARNING) << "fcntl #1 failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000993 }
994 if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100995 RTC_LOG_ERR(LS_WARNING) << "fcntl #2 failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000996 }
Yves Gerey665174f2018-06-19 15:03:05 +0200997 memset(const_cast<void*>(static_cast<volatile void*>(received_signal_)), 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000998 sizeof(received_signal_));
999 }
1000
1001 ~PosixSignalHandler() {
1002 int fd1 = afd_[0];
1003 int fd2 = afd_[1];
1004 // We clobber the stored file descriptor numbers here or else in principle
1005 // a signal that happens to be delivered during application termination
1006 // could erroneously write a zero byte to an unrelated file handle in
1007 // OnPosixSignalReceived() if some other file happens to be opened later
1008 // during shutdown and happens to be given the same file descriptor number
1009 // as our pipe had. Unfortunately even with this precaution there is still a
1010 // race where that could occur if said signal happens to be handled
1011 // concurrently with this code and happens to have already read the value of
1012 // afd_[1] from memory before we clobber it, but that's unlikely.
1013 afd_[0] = -1;
1014 afd_[1] = -1;
1015 close(fd1);
1016 close(fd2);
1017 }
1018
1019 int afd_[2];
1020 // These are boolean flags that will be set in our signal handler and read
1021 // and cleared from Wait(). There is a race involved in this, but it is
1022 // benign. The signal handler sets the flag before signaling the pipe, so
1023 // we'll never end up blocking in select() while a flag is still true.
1024 // However, if two of the same signal arrive close to each other then it's
1025 // possible that the second time the handler may set the flag while it's still
1026 // true, meaning that signal will be missed. But the first occurrence of it
1027 // will still be handled, so this isn't a problem.
1028 // Volatile is not necessary here for correctness, but this data _is_ volatile
1029 // so I've marked it as such.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001030 volatile uint8_t received_signal_[kNumPosixSignals];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001031};
1032
1033class PosixSignalDispatcher : public Dispatcher {
1034 public:
Yves Gerey665174f2018-06-19 15:03:05 +02001035 PosixSignalDispatcher(PhysicalSocketServer* owner) : owner_(owner) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001036 owner_->Add(this);
1037 }
1038
Yves Gerey665174f2018-06-19 15:03:05 +02001039 ~PosixSignalDispatcher() override { owner_->Remove(this); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001040
Peter Boström0c4e06b2015-10-07 12:23:21 +02001041 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001042
Peter Boström0c4e06b2015-10-07 12:23:21 +02001043 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001044 // Events might get grouped if signals come very fast, so we read out up to
1045 // 16 bytes to make sure we keep the pipe empty.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001046 uint8_t b[16];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001047 ssize_t ret = read(GetDescriptor(), b, sizeof(b));
1048 if (ret < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001049 RTC_LOG_ERR(LS_WARNING) << "Error in read()";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001050 } else if (ret == 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001051 RTC_LOG(LS_WARNING) << "Should have read at least one byte";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001052 }
1053 }
1054
Peter Boström0c4e06b2015-10-07 12:23:21 +02001055 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001056 for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
1057 ++signum) {
1058 if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
1059 PosixSignalHandler::Instance()->ClearSignal(signum);
1060 HandlerMap::iterator i = handlers_.find(signum);
1061 if (i == handlers_.end()) {
1062 // This can happen if a signal is delivered to our process at around
1063 // the same time as we unset our handler for it. It is not an error
1064 // condition, but it's unusual enough to be worth logging.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001065 RTC_LOG(LS_INFO) << "Received signal with no handler: " << signum;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001066 } else {
1067 // Otherwise, execute our handler.
1068 (*i->second)(signum);
1069 }
1070 }
1071 }
1072 }
1073
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001074 int GetDescriptor() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001075 return PosixSignalHandler::Instance()->GetDescriptor();
1076 }
1077
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001078 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001079
1080 void SetHandler(int signum, void (*handler)(int)) {
1081 handlers_[signum] = handler;
1082 }
1083
Yves Gerey665174f2018-06-19 15:03:05 +02001084 void ClearHandler(int signum) { handlers_.erase(signum); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001085
Yves Gerey665174f2018-06-19 15:03:05 +02001086 bool HasHandlers() { return !handlers_.empty(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001087
1088 private:
1089 typedef std::map<int, void (*)(int)> HandlerMap;
1090
1091 HandlerMap handlers_;
1092 // Our owner.
Yves Gerey665174f2018-06-19 15:03:05 +02001093 PhysicalSocketServer* owner_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001094};
1095
Yves Gerey665174f2018-06-19 15:03:05 +02001096#endif // WEBRTC_POSIX
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001097
1098#if defined(WEBRTC_WIN)
Peter Boström0c4e06b2015-10-07 12:23:21 +02001099static uint32_t FlagsToEvents(uint32_t events) {
1100 uint32_t ffFD = FD_CLOSE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001101 if (events & DE_READ)
1102 ffFD |= FD_READ;
1103 if (events & DE_WRITE)
1104 ffFD |= FD_WRITE;
1105 if (events & DE_CONNECT)
1106 ffFD |= FD_CONNECT;
1107 if (events & DE_ACCEPT)
1108 ffFD |= FD_ACCEPT;
1109 return ffFD;
1110}
1111
1112class EventDispatcher : public Dispatcher {
1113 public:
Yves Gerey665174f2018-06-19 15:03:05 +02001114 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001115 hev_ = WSACreateEvent();
1116 if (hev_) {
1117 ss_->Add(this);
1118 }
1119 }
1120
Steve Anton9de3aac2017-10-24 10:08:26 -07001121 ~EventDispatcher() override {
deadbeef37f5ecf2017-02-27 14:06:41 -08001122 if (hev_ != nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001123 ss_->Remove(this);
1124 WSACloseEvent(hev_);
deadbeef37f5ecf2017-02-27 14:06:41 -08001125 hev_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001126 }
1127 }
1128
1129 virtual void Signal() {
deadbeef37f5ecf2017-02-27 14:06:41 -08001130 if (hev_ != nullptr)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001131 WSASetEvent(hev_);
1132 }
1133
Steve Anton9de3aac2017-10-24 10:08:26 -07001134 uint32_t GetRequestedEvents() override { return 0; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001135
Steve Anton9de3aac2017-10-24 10:08:26 -07001136 void OnPreEvent(uint32_t ff) override { WSAResetEvent(hev_); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001137
Steve Anton9de3aac2017-10-24 10:08:26 -07001138 void OnEvent(uint32_t ff, int err) override {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001139
Steve Anton9de3aac2017-10-24 10:08:26 -07001140 WSAEVENT GetWSAEvent() override { return hev_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001141
Steve Anton9de3aac2017-10-24 10:08:26 -07001142 SOCKET GetSocket() override { return INVALID_SOCKET; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001143
Steve Anton9de3aac2017-10-24 10:08:26 -07001144 bool CheckSignalClose() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001145
Steve Anton9de3aac2017-10-24 10:08:26 -07001146 private:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001147 PhysicalSocketServer* ss_;
1148 WSAEVENT hev_;
1149};
honghaizcec0a082016-01-15 14:49:09 -08001150#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001151
1152// Sets the value of a boolean value to false when signaled.
1153class Signaler : public EventDispatcher {
1154 public:
Yves Gerey665174f2018-06-19 15:03:05 +02001155 Signaler(PhysicalSocketServer* ss, bool* pf) : EventDispatcher(ss), pf_(pf) {}
1156 ~Signaler() override {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001157
Peter Boström0c4e06b2015-10-07 12:23:21 +02001158 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001159 if (pf_)
1160 *pf_ = false;
1161 }
1162
1163 private:
Yves Gerey665174f2018-06-19 15:03:05 +02001164 bool* pf_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001165};
1166
Yves Gerey665174f2018-06-19 15:03:05 +02001167PhysicalSocketServer::PhysicalSocketServer() : fWait_(false) {
jbauchde4db112017-05-31 13:09:18 -07001168#if defined(WEBRTC_USE_EPOLL)
1169 // Since Linux 2.6.8, the size argument is ignored, but must be greater than
1170 // zero. Before that the size served as hint to the kernel for the amount of
1171 // space to initially allocate in internal data structures.
1172 epoll_fd_ = epoll_create(FD_SETSIZE);
1173 if (epoll_fd_ == -1) {
1174 // Not an error, will fall back to "select" below.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001175 RTC_LOG_E(LS_WARNING, EN, errno) << "epoll_create";
jbauchde4db112017-05-31 13:09:18 -07001176 epoll_fd_ = INVALID_SOCKET;
1177 }
1178#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001179 signal_wakeup_ = new Signaler(this, &fWait_);
1180#if defined(WEBRTC_WIN)
1181 socket_ev_ = WSACreateEvent();
1182#endif
1183}
1184
1185PhysicalSocketServer::~PhysicalSocketServer() {
1186#if defined(WEBRTC_WIN)
1187 WSACloseEvent(socket_ev_);
1188#endif
1189#if defined(WEBRTC_POSIX)
1190 signal_dispatcher_.reset();
1191#endif
1192 delete signal_wakeup_;
jbauchde4db112017-05-31 13:09:18 -07001193#if defined(WEBRTC_USE_EPOLL)
1194 if (epoll_fd_ != INVALID_SOCKET) {
1195 close(epoll_fd_);
1196 }
1197#endif
nisseede5da42017-01-12 05:15:36 -08001198 RTC_DCHECK(dispatchers_.empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001199}
1200
1201void PhysicalSocketServer::WakeUp() {
1202 signal_wakeup_->Signal();
1203}
1204
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001205Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
1206 PhysicalSocket* socket = new PhysicalSocket(this);
1207 if (socket->Create(family, type)) {
1208 return socket;
1209 } else {
1210 delete socket;
jbauch095ae152015-12-18 01:39:55 -08001211 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001212 }
1213}
1214
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001215AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
1216 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1217 if (dispatcher->Create(family, type)) {
1218 return dispatcher;
1219 } else {
1220 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001221 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001222 }
1223}
1224
1225AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
1226 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1227 if (dispatcher->Initialize()) {
1228 return dispatcher;
1229 } else {
1230 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001231 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001232 }
1233}
1234
Yves Gerey665174f2018-06-19 15:03:05 +02001235void PhysicalSocketServer::Add(Dispatcher* pdispatcher) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001236 CritScope cs(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001237 if (processing_dispatchers_) {
1238 // A dispatcher is being added while a "Wait" call is processing the
1239 // list of socket events.
1240 // Defer adding to "dispatchers_" set until processing is done to avoid
1241 // invalidating the iterator in "Wait".
1242 pending_remove_dispatchers_.erase(pdispatcher);
1243 pending_add_dispatchers_.insert(pdispatcher);
1244 } else {
1245 dispatchers_.insert(pdispatcher);
1246 }
1247#if defined(WEBRTC_USE_EPOLL)
1248 if (epoll_fd_ != INVALID_SOCKET) {
1249 AddEpoll(pdispatcher);
1250 }
1251#endif // WEBRTC_USE_EPOLL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001252}
1253
Yves Gerey665174f2018-06-19 15:03:05 +02001254void PhysicalSocketServer::Remove(Dispatcher* pdispatcher) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001255 CritScope cs(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001256 if (processing_dispatchers_) {
1257 // A dispatcher is being removed while a "Wait" call is processing the
1258 // list of socket events.
1259 // Defer removal from "dispatchers_" set until processing is done to avoid
1260 // invalidating the iterator in "Wait".
1261 if (!pending_add_dispatchers_.erase(pdispatcher) &&
1262 dispatchers_.find(pdispatcher) == dispatchers_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001263 RTC_LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
1264 << "dispatcher, potentially from a duplicate call to "
1265 << "Add.";
jbauchde4db112017-05-31 13:09:18 -07001266 return;
1267 }
1268
1269 pending_remove_dispatchers_.insert(pdispatcher);
1270 } else if (!dispatchers_.erase(pdispatcher)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001271 RTC_LOG(LS_WARNING)
1272 << "PhysicalSocketServer asked to remove a unknown "
1273 << "dispatcher, potentially from a duplicate call to Add.";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001274 return;
1275 }
jbauchde4db112017-05-31 13:09:18 -07001276#if defined(WEBRTC_USE_EPOLL)
1277 if (epoll_fd_ != INVALID_SOCKET) {
1278 RemoveEpoll(pdispatcher);
1279 }
1280#endif // WEBRTC_USE_EPOLL
1281}
1282
1283void PhysicalSocketServer::Update(Dispatcher* pdispatcher) {
1284#if defined(WEBRTC_USE_EPOLL)
1285 if (epoll_fd_ == INVALID_SOCKET) {
1286 return;
1287 }
1288
1289 CritScope cs(&crit_);
1290 if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1291 return;
1292 }
1293
1294 UpdateEpoll(pdispatcher);
1295#endif
1296}
1297
1298void PhysicalSocketServer::AddRemovePendingDispatchers() {
1299 if (!pending_add_dispatchers_.empty()) {
1300 for (Dispatcher* pdispatcher : pending_add_dispatchers_) {
1301 dispatchers_.insert(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001302 }
jbauchde4db112017-05-31 13:09:18 -07001303 pending_add_dispatchers_.clear();
1304 }
1305
1306 if (!pending_remove_dispatchers_.empty()) {
1307 for (Dispatcher* pdispatcher : pending_remove_dispatchers_) {
1308 dispatchers_.erase(pdispatcher);
1309 }
1310 pending_remove_dispatchers_.clear();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001311 }
1312}
1313
1314#if defined(WEBRTC_POSIX)
jbauchde4db112017-05-31 13:09:18 -07001315
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001316bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
jbauchde4db112017-05-31 13:09:18 -07001317#if defined(WEBRTC_USE_EPOLL)
1318 // We don't keep a dedicated "epoll" descriptor containing only the non-IO
1319 // (i.e. signaling) dispatcher, so "poll" will be used instead of the default
1320 // "select" to support sockets larger than FD_SETSIZE.
1321 if (!process_io) {
1322 return WaitPoll(cmsWait, signal_wakeup_);
1323 } else if (epoll_fd_ != INVALID_SOCKET) {
1324 return WaitEpoll(cmsWait);
1325 }
1326#endif
1327 return WaitSelect(cmsWait, process_io);
1328}
1329
1330static void ProcessEvents(Dispatcher* dispatcher,
1331 bool readable,
1332 bool writable,
1333 bool check_error) {
1334 int errcode = 0;
1335 // TODO(pthatcher): Should we set errcode if getsockopt fails?
1336 if (check_error) {
1337 socklen_t len = sizeof(errcode);
1338 ::getsockopt(dispatcher->GetDescriptor(), SOL_SOCKET, SO_ERROR, &errcode,
1339 &len);
1340 }
1341
1342 uint32_t ff = 0;
1343
1344 // Check readable descriptors. If we're waiting on an accept, signal
1345 // that. Otherwise we're waiting for data, check to see if we're
1346 // readable or really closed.
1347 // TODO(pthatcher): Only peek at TCP descriptors.
1348 if (readable) {
1349 if (dispatcher->GetRequestedEvents() & DE_ACCEPT) {
1350 ff |= DE_ACCEPT;
1351 } else if (errcode || dispatcher->IsDescriptorClosed()) {
1352 ff |= DE_CLOSE;
1353 } else {
1354 ff |= DE_READ;
1355 }
1356 }
1357
1358 // Check writable descriptors. If we're waiting on a connect, detect
1359 // success versus failure by the reaped error code.
1360 if (writable) {
1361 if (dispatcher->GetRequestedEvents() & DE_CONNECT) {
1362 if (!errcode) {
1363 ff |= DE_CONNECT;
1364 } else {
1365 ff |= DE_CLOSE;
1366 }
1367 } else {
1368 ff |= DE_WRITE;
1369 }
1370 }
1371
1372 // Tell the descriptor about the event.
1373 if (ff != 0) {
1374 dispatcher->OnPreEvent(ff);
1375 dispatcher->OnEvent(ff, errcode);
1376 }
1377}
1378
1379bool PhysicalSocketServer::WaitSelect(int cmsWait, bool process_io) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001380 // Calculate timing information
1381
deadbeef37f5ecf2017-02-27 14:06:41 -08001382 struct timeval* ptvWait = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001383 struct timeval tvWait;
Niels Möller689b5872018-08-29 09:55:44 +02001384 int64_t stop_us;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001385 if (cmsWait != kForever) {
1386 // Calculate wait timeval
1387 tvWait.tv_sec = cmsWait / 1000;
1388 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1389 ptvWait = &tvWait;
1390
Niels Möller689b5872018-08-29 09:55:44 +02001391 // Calculate when to return
1392 stop_us = rtc::TimeMicros() + cmsWait * 1000;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001393 }
1394
1395 // Zero all fd_sets. Don't need to do this inside the loop since
1396 // select() zeros the descriptors not signaled
1397
1398 fd_set fdsRead;
1399 FD_ZERO(&fdsRead);
1400 fd_set fdsWrite;
1401 FD_ZERO(&fdsWrite);
Yves Gerey665174f2018-06-19 15:03:05 +02001402// Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1403// inline assembly in FD_ZERO.
1404// http://crbug.com/344505
pbos@webrtc.org27e58982014-10-07 17:56:53 +00001405#ifdef MEMORY_SANITIZER
1406 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1407 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1408#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001409
1410 fWait_ = true;
1411
1412 while (fWait_) {
1413 int fdmax = -1;
1414 {
1415 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001416 // TODO(jbauch): Support re-entrant waiting.
1417 RTC_DCHECK(!processing_dispatchers_);
1418 for (Dispatcher* pdispatcher : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001419 // Query dispatchers for read and write wait state
nisseede5da42017-01-12 05:15:36 -08001420 RTC_DCHECK(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001421 if (!process_io && (pdispatcher != signal_wakeup_))
1422 continue;
1423 int fd = pdispatcher->GetDescriptor();
jbauchde4db112017-05-31 13:09:18 -07001424 // "select"ing a file descriptor that is equal to or larger than
1425 // FD_SETSIZE will result in undefined behavior.
1426 RTC_DCHECK_LT(fd, FD_SETSIZE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001427 if (fd > fdmax)
1428 fdmax = fd;
1429
Peter Boström0c4e06b2015-10-07 12:23:21 +02001430 uint32_t ff = pdispatcher->GetRequestedEvents();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001431 if (ff & (DE_READ | DE_ACCEPT))
1432 FD_SET(fd, &fdsRead);
1433 if (ff & (DE_WRITE | DE_CONNECT))
1434 FD_SET(fd, &fdsWrite);
1435 }
1436 }
1437
1438 // Wait then call handlers as appropriate
1439 // < 0 means error
1440 // 0 means timeout
1441 // > 0 means count of descriptors ready
deadbeef37f5ecf2017-02-27 14:06:41 -08001442 int n = select(fdmax + 1, &fdsRead, &fdsWrite, nullptr, ptvWait);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001443
1444 // If error, return error.
1445 if (n < 0) {
1446 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001447 RTC_LOG_E(LS_ERROR, EN, errno) << "select";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001448 return false;
1449 }
1450 // Else ignore the error and keep going. If this EINTR was for one of the
1451 // signals managed by this PhysicalSocketServer, the
1452 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1453 // iteration.
1454 } else if (n == 0) {
1455 // If timeout, return success
1456 return true;
1457 } else {
1458 // We have signaled descriptors
1459 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001460 processing_dispatchers_ = true;
1461 for (Dispatcher* pdispatcher : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001462 int fd = pdispatcher->GetDescriptor();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001463
jbauchde4db112017-05-31 13:09:18 -07001464 bool readable = FD_ISSET(fd, &fdsRead);
1465 if (readable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001466 FD_CLR(fd, &fdsRead);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001467 }
1468
jbauchde4db112017-05-31 13:09:18 -07001469 bool writable = FD_ISSET(fd, &fdsWrite);
1470 if (writable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001471 FD_CLR(fd, &fdsWrite);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001472 }
1473
jbauchde4db112017-05-31 13:09:18 -07001474 // The error code can be signaled through reads or writes.
1475 ProcessEvents(pdispatcher, readable, writable, readable || writable);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001476 }
jbauchde4db112017-05-31 13:09:18 -07001477
1478 processing_dispatchers_ = false;
1479 // Process deferred dispatchers that have been added/removed while the
1480 // events were handled above.
1481 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001482 }
1483
1484 // Recalc the time remaining to wait. Doing it here means it doesn't get
1485 // calced twice the first time through the loop
1486 if (ptvWait) {
1487 ptvWait->tv_sec = 0;
1488 ptvWait->tv_usec = 0;
Niels Möller689b5872018-08-29 09:55:44 +02001489 int64_t time_left_us = stop_us - rtc::TimeMicros();
1490 if (time_left_us > 0) {
1491 ptvWait->tv_sec = time_left_us / rtc::kNumMicrosecsPerSec;
1492 ptvWait->tv_usec = time_left_us % rtc::kNumMicrosecsPerSec;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001493 }
1494 }
1495 }
1496
1497 return true;
1498}
1499
jbauchde4db112017-05-31 13:09:18 -07001500#if defined(WEBRTC_USE_EPOLL)
1501
1502// Initial number of events to process with one call to "epoll_wait".
1503static const size_t kInitialEpollEvents = 128;
1504
1505// Maximum number of events to process with one call to "epoll_wait".
1506static const size_t kMaxEpollEvents = 8192;
1507
1508void PhysicalSocketServer::AddEpoll(Dispatcher* pdispatcher) {
1509 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1510 int fd = pdispatcher->GetDescriptor();
1511 RTC_DCHECK(fd != INVALID_SOCKET);
1512 if (fd == INVALID_SOCKET) {
1513 return;
1514 }
1515
1516 struct epoll_event event = {0};
1517 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
1518 event.data.ptr = pdispatcher;
1519 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &event);
1520 RTC_DCHECK_EQ(err, 0);
1521 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001522 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_ADD";
jbauchde4db112017-05-31 13:09:18 -07001523 }
1524}
1525
1526void PhysicalSocketServer::RemoveEpoll(Dispatcher* pdispatcher) {
1527 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1528 int fd = pdispatcher->GetDescriptor();
1529 RTC_DCHECK(fd != INVALID_SOCKET);
1530 if (fd == INVALID_SOCKET) {
1531 return;
1532 }
1533
1534 struct epoll_event event = {0};
1535 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &event);
1536 RTC_DCHECK(err == 0 || errno == ENOENT);
1537 if (err == -1) {
1538 if (errno == ENOENT) {
1539 // Socket has already been closed.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001540 RTC_LOG_E(LS_VERBOSE, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001541 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001542 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001543 }
1544 }
1545}
1546
1547void PhysicalSocketServer::UpdateEpoll(Dispatcher* pdispatcher) {
1548 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1549 int fd = pdispatcher->GetDescriptor();
1550 RTC_DCHECK(fd != INVALID_SOCKET);
1551 if (fd == INVALID_SOCKET) {
1552 return;
1553 }
1554
1555 struct epoll_event event = {0};
1556 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
1557 event.data.ptr = pdispatcher;
1558 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &event);
1559 RTC_DCHECK_EQ(err, 0);
1560 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001561 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_MOD";
jbauchde4db112017-05-31 13:09:18 -07001562 }
1563}
1564
1565bool PhysicalSocketServer::WaitEpoll(int cmsWait) {
1566 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1567 int64_t tvWait = -1;
1568 int64_t tvStop = -1;
1569 if (cmsWait != kForever) {
1570 tvWait = cmsWait;
1571 tvStop = TimeAfter(cmsWait);
1572 }
1573
1574 if (epoll_events_.empty()) {
1575 // The initial space to receive events is created only if epoll is used.
1576 epoll_events_.resize(kInitialEpollEvents);
1577 }
1578
1579 fWait_ = true;
1580
1581 while (fWait_) {
1582 // Wait then call handlers as appropriate
1583 // < 0 means error
1584 // 0 means timeout
1585 // > 0 means count of descriptors ready
1586 int n = epoll_wait(epoll_fd_, &epoll_events_[0],
1587 static_cast<int>(epoll_events_.size()),
1588 static_cast<int>(tvWait));
1589 if (n < 0) {
1590 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001591 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll";
jbauchde4db112017-05-31 13:09:18 -07001592 return false;
1593 }
1594 // Else ignore the error and keep going. If this EINTR was for one of the
1595 // signals managed by this PhysicalSocketServer, the
1596 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1597 // iteration.
1598 } else if (n == 0) {
1599 // If timeout, return success
1600 return true;
1601 } else {
1602 // We have signaled descriptors
1603 CritScope cr(&crit_);
1604 for (int i = 0; i < n; ++i) {
1605 const epoll_event& event = epoll_events_[i];
1606 Dispatcher* pdispatcher = static_cast<Dispatcher*>(event.data.ptr);
1607 if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1608 // The dispatcher for this socket no longer exists.
1609 continue;
1610 }
1611
1612 bool readable = (event.events & (EPOLLIN | EPOLLPRI));
1613 bool writable = (event.events & EPOLLOUT);
1614 bool check_error = (event.events & (EPOLLRDHUP | EPOLLERR | EPOLLHUP));
1615
1616 ProcessEvents(pdispatcher, readable, writable, check_error);
1617 }
1618 }
1619
1620 if (static_cast<size_t>(n) == epoll_events_.size() &&
1621 epoll_events_.size() < kMaxEpollEvents) {
1622 // We used the complete space to receive events, increase size for future
1623 // iterations.
1624 epoll_events_.resize(std::max(epoll_events_.size() * 2, kMaxEpollEvents));
1625 }
1626
1627 if (cmsWait != kForever) {
1628 tvWait = TimeDiff(tvStop, TimeMillis());
1629 if (tvWait < 0) {
1630 // Return success on timeout.
1631 return true;
1632 }
1633 }
1634 }
1635
1636 return true;
1637}
1638
1639bool PhysicalSocketServer::WaitPoll(int cmsWait, Dispatcher* dispatcher) {
1640 RTC_DCHECK(dispatcher);
1641 int64_t tvWait = -1;
1642 int64_t tvStop = -1;
1643 if (cmsWait != kForever) {
1644 tvWait = cmsWait;
1645 tvStop = TimeAfter(cmsWait);
1646 }
1647
1648 fWait_ = true;
1649
1650 struct pollfd fds = {0};
1651 int fd = dispatcher->GetDescriptor();
1652 fds.fd = fd;
1653
1654 while (fWait_) {
1655 uint32_t ff = dispatcher->GetRequestedEvents();
1656 fds.events = 0;
1657 if (ff & (DE_READ | DE_ACCEPT)) {
1658 fds.events |= POLLIN;
1659 }
1660 if (ff & (DE_WRITE | DE_CONNECT)) {
1661 fds.events |= POLLOUT;
1662 }
1663 fds.revents = 0;
1664
1665 // Wait then call handlers as appropriate
1666 // < 0 means error
1667 // 0 means timeout
1668 // > 0 means count of descriptors ready
1669 int n = poll(&fds, 1, static_cast<int>(tvWait));
1670 if (n < 0) {
1671 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001672 RTC_LOG_E(LS_ERROR, EN, errno) << "poll";
jbauchde4db112017-05-31 13:09:18 -07001673 return false;
1674 }
1675 // Else ignore the error and keep going. If this EINTR was for one of the
1676 // signals managed by this PhysicalSocketServer, the
1677 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1678 // iteration.
1679 } else if (n == 0) {
1680 // If timeout, return success
1681 return true;
1682 } else {
1683 // We have signaled descriptors (should only be the passed dispatcher).
1684 RTC_DCHECK_EQ(n, 1);
1685 RTC_DCHECK_EQ(fds.fd, fd);
1686
1687 bool readable = (fds.revents & (POLLIN | POLLPRI));
1688 bool writable = (fds.revents & POLLOUT);
1689 bool check_error = (fds.revents & (POLLRDHUP | POLLERR | POLLHUP));
1690
1691 ProcessEvents(dispatcher, readable, writable, check_error);
1692 }
1693
1694 if (cmsWait != kForever) {
1695 tvWait = TimeDiff(tvStop, TimeMillis());
1696 if (tvWait < 0) {
1697 // Return success on timeout.
1698 return true;
1699 }
1700 }
1701 }
1702
1703 return true;
1704}
1705
1706#endif // WEBRTC_USE_EPOLL
1707
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001708static void GlobalSignalHandler(int signum) {
1709 PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
1710}
1711
1712bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
1713 void (*handler)(int)) {
1714 // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
1715 // otherwise set one.
1716 if (handler == SIG_IGN || handler == SIG_DFL) {
1717 if (!InstallSignal(signum, handler)) {
1718 return false;
1719 }
1720 if (signal_dispatcher_) {
1721 signal_dispatcher_->ClearHandler(signum);
1722 if (!signal_dispatcher_->HasHandlers()) {
1723 signal_dispatcher_.reset();
1724 }
1725 }
1726 } else {
1727 if (!signal_dispatcher_) {
1728 signal_dispatcher_.reset(new PosixSignalDispatcher(this));
1729 }
1730 signal_dispatcher_->SetHandler(signum, handler);
1731 if (!InstallSignal(signum, &GlobalSignalHandler)) {
1732 return false;
1733 }
1734 }
1735 return true;
1736}
1737
1738Dispatcher* PhysicalSocketServer::signal_dispatcher() {
1739 return signal_dispatcher_.get();
1740}
1741
1742bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
1743 struct sigaction act;
1744 // It doesn't really matter what we set this mask to.
1745 if (sigemptyset(&act.sa_mask) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001746 RTC_LOG_ERR(LS_ERROR) << "Couldn't set mask";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001747 return false;
1748 }
1749 act.sa_handler = handler;
1750#if !defined(__native_client__)
1751 // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
1752 // and it's a nuisance. Though some syscalls still return EINTR and there's no
1753 // real standard for which ones. :(
1754 act.sa_flags = SA_RESTART;
1755#else
1756 act.sa_flags = 0;
1757#endif
deadbeef37f5ecf2017-02-27 14:06:41 -08001758 if (sigaction(signum, &act, nullptr) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001759 RTC_LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001760 return false;
1761 }
1762 return true;
1763}
1764#endif // WEBRTC_POSIX
1765
1766#if defined(WEBRTC_WIN)
1767bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
Honghai Zhang82d78622016-05-06 11:29:15 -07001768 int64_t cmsTotal = cmsWait;
1769 int64_t cmsElapsed = 0;
1770 int64_t msStart = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001771
1772 fWait_ = true;
1773 while (fWait_) {
1774 std::vector<WSAEVENT> events;
Yves Gerey665174f2018-06-19 15:03:05 +02001775 std::vector<Dispatcher*> event_owners;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001776
1777 events.push_back(socket_ev_);
1778
1779 {
1780 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001781 // TODO(jbauch): Support re-entrant waiting.
1782 RTC_DCHECK(!processing_dispatchers_);
1783
1784 // Calling "CheckSignalClose" might remove a closed dispatcher from the
1785 // set. This must be deferred to prevent invalidating the iterator.
1786 processing_dispatchers_ = true;
1787 for (Dispatcher* disp : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001788 if (!process_io && (disp != signal_wakeup_))
1789 continue;
1790 SOCKET s = disp->GetSocket();
1791 if (disp->CheckSignalClose()) {
1792 // We just signalled close, don't poll this socket
1793 } else if (s != INVALID_SOCKET) {
Yves Gerey665174f2018-06-19 15:03:05 +02001794 WSAEventSelect(s, events[0],
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001795 FlagsToEvents(disp->GetRequestedEvents()));
1796 } else {
1797 events.push_back(disp->GetWSAEvent());
1798 event_owners.push_back(disp);
1799 }
1800 }
jbauchde4db112017-05-31 13:09:18 -07001801
1802 processing_dispatchers_ = false;
1803 // Process deferred dispatchers that have been added/removed while the
1804 // events were handled above.
1805 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001806 }
1807
1808 // Which is shorter, the delay wait or the asked wait?
1809
Honghai Zhang82d78622016-05-06 11:29:15 -07001810 int64_t cmsNext;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001811 if (cmsWait == kForever) {
1812 cmsNext = cmsWait;
1813 } else {
Honghai Zhang82d78622016-05-06 11:29:15 -07001814 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001815 }
1816
1817 // Wait for one of the events to signal
Yves Gerey665174f2018-06-19 15:03:05 +02001818 DWORD dw =
1819 WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()), &events[0],
1820 false, static_cast<DWORD>(cmsNext), false);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001821
1822 if (dw == WSA_WAIT_FAILED) {
1823 // Failed?
jbauch095ae152015-12-18 01:39:55 -08001824 // TODO(pthatcher): need a better strategy than this!
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001825 WSAGetLastError();
nissec80e7412017-01-11 05:56:46 -08001826 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001827 return false;
1828 } else if (dw == WSA_WAIT_TIMEOUT) {
1829 // Timeout?
1830 return true;
1831 } else {
1832 // Figure out which one it is and call it
1833 CritScope cr(&crit_);
1834 int index = dw - WSA_WAIT_EVENT_0;
1835 if (index > 0) {
Yves Gerey665174f2018-06-19 15:03:05 +02001836 --index; // The first event is the socket event
jbauchde4db112017-05-31 13:09:18 -07001837 Dispatcher* disp = event_owners[index];
1838 // The dispatcher could have been removed while waiting for events.
1839 if (dispatchers_.find(disp) != dispatchers_.end()) {
1840 disp->OnPreEvent(0);
1841 disp->OnEvent(0, 0);
1842 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001843 } else if (process_io) {
jbauchde4db112017-05-31 13:09:18 -07001844 processing_dispatchers_ = true;
1845 for (Dispatcher* disp : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001846 SOCKET s = disp->GetSocket();
1847 if (s == INVALID_SOCKET)
1848 continue;
1849
1850 WSANETWORKEVENTS wsaEvents;
1851 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1852 if (err == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001853 {
1854 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1855 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001856 RTC_LOG(WARNING)
1857 << "PhysicalSocketServer got FD_READ_BIT error "
1858 << wsaEvents.iErrorCode[FD_READ_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001859 }
1860 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1861 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001862 RTC_LOG(WARNING)
1863 << "PhysicalSocketServer got FD_WRITE_BIT error "
1864 << wsaEvents.iErrorCode[FD_WRITE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001865 }
1866 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1867 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001868 RTC_LOG(WARNING)
1869 << "PhysicalSocketServer got FD_CONNECT_BIT error "
1870 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001871 }
1872 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1873 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001874 RTC_LOG(WARNING)
1875 << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1876 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001877 }
1878 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1879 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001880 RTC_LOG(WARNING)
1881 << "PhysicalSocketServer got FD_CLOSE_BIT error "
1882 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001883 }
1884 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001885 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001886 int errcode = 0;
1887 if (wsaEvents.lNetworkEvents & FD_READ)
1888 ff |= DE_READ;
1889 if (wsaEvents.lNetworkEvents & FD_WRITE)
1890 ff |= DE_WRITE;
1891 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1892 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1893 ff |= DE_CONNECT;
1894 } else {
1895 ff |= DE_CLOSE;
1896 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1897 }
1898 }
1899 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1900 ff |= DE_ACCEPT;
1901 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1902 ff |= DE_CLOSE;
1903 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1904 }
1905 if (ff != 0) {
1906 disp->OnPreEvent(ff);
1907 disp->OnEvent(ff, errcode);
1908 }
1909 }
1910 }
jbauchde4db112017-05-31 13:09:18 -07001911
1912 processing_dispatchers_ = false;
1913 // Process deferred dispatchers that have been added/removed while the
1914 // events were handled above.
1915 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001916 }
1917
1918 // Reset the network event until new activity occurs
1919 WSAResetEvent(socket_ev_);
1920 }
1921
1922 // Break?
1923 if (!fWait_)
1924 break;
1925 cmsElapsed = TimeSince(msStart);
1926 if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
Yves Gerey665174f2018-06-19 15:03:05 +02001927 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001928 }
1929 }
1930
1931 // Done
1932 return true;
1933}
honghaizcec0a082016-01-15 14:49:09 -08001934#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001935
1936} // namespace rtc