blob: 22a3882bd431c86a447cc85469d22fd369f6d0fe [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020010#include "rtc_base/physicalsocketserver.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000011
12#if defined(_MSC_VER) && _MSC_VER < 1300
13#pragma warning(disable:4786)
14#endif
15
pbos@webrtc.org27e58982014-10-07 17:56:53 +000016#ifdef MEMORY_SANITIZER
17#include <sanitizer/msan_interface.h>
18#endif
19
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000020#if defined(WEBRTC_POSIX)
21#include <string.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000022#include <fcntl.h>
jbauchde4db112017-05-31 13:09:18 -070023#if defined(WEBRTC_USE_EPOLL)
24// "poll" will be used to wait for the signal dispatcher.
25#include <poll.h>
26#endif
Stefan Holmer9131efd2016-05-23 18:19:26 +020027#include <sys/ioctl.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000028#include <sys/time.h>
29#include <sys/select.h>
30#include <unistd.h>
31#include <signal.h>
32#endif
33
34#if defined(WEBRTC_WIN)
35#define WIN32_LEAN_AND_MEAN
36#include <windows.h>
37#include <winsock2.h>
38#include <ws2tcpip.h>
39#undef SetPort
40#endif
41
Patrik Höglunda8005cf2017-12-13 16:05:42 +010042#include <errno.h>
43
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000044#include <algorithm>
45#include <map>
46
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "rtc_base/arraysize.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "rtc_base/byteorder.h"
49#include "rtc_base/checks.h"
50#include "rtc_base/logging.h"
51#include "rtc_base/networkmonitor.h"
52#include "rtc_base/nullsocketserver.h"
53#include "rtc_base/timeutils.h"
54#include "rtc_base/win32socketinit.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000055
Patrik Höglunda8005cf2017-12-13 16:05:42 +010056#if defined(WEBRTC_WIN)
57#define LAST_SYSTEM_ERROR (::GetLastError())
58#elif defined(__native_client__) && __native_client__
59#define LAST_SYSTEM_ERROR (0)
60#elif defined(WEBRTC_POSIX)
61#define LAST_SYSTEM_ERROR (errno)
62#endif // WEBRTC_WIN
63
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000064#if defined(WEBRTC_POSIX)
65#include <netinet/tcp.h> // for TCP_NODELAY
66#define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h
67typedef void* SockOptArg;
Stefan Holmer9131efd2016-05-23 18:19:26 +020068
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000069#endif // WEBRTC_POSIX
70
Stefan Holmer3ebb3ef2016-05-23 20:26:11 +020071#if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) && !defined(__native_client__)
72
Stefan Holmer9131efd2016-05-23 18:19:26 +020073int64_t GetSocketRecvTimestamp(int socket) {
74 struct timeval tv_ioctl;
75 int ret = ioctl(socket, SIOCGSTAMP, &tv_ioctl);
76 if (ret != 0)
77 return -1;
78 int64_t timestamp =
79 rtc::kNumMicrosecsPerSec * static_cast<int64_t>(tv_ioctl.tv_sec) +
80 static_cast<int64_t>(tv_ioctl.tv_usec);
81 return timestamp;
82}
83
84#else
85
86int64_t GetSocketRecvTimestamp(int socket) {
87 return -1;
88}
89#endif
90
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000091#if defined(WEBRTC_WIN)
92typedef char* SockOptArg;
93#endif
94
jbauchde4db112017-05-31 13:09:18 -070095#if defined(WEBRTC_USE_EPOLL)
96// POLLRDHUP / EPOLLRDHUP are only defined starting with Linux 2.6.17.
97#if !defined(POLLRDHUP)
98#define POLLRDHUP 0x2000
99#endif
100#if !defined(EPOLLRDHUP)
101#define EPOLLRDHUP 0x2000
102#endif
103#endif
104
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000105namespace rtc {
106
danilchapbebf54c2016-04-28 01:32:48 -0700107std::unique_ptr<SocketServer> SocketServer::CreateDefault() {
108#if defined(__native_client__)
109 return std::unique_ptr<SocketServer>(new rtc::NullSocketServer);
110#else
111 return std::unique_ptr<SocketServer>(new rtc::PhysicalSocketServer);
112#endif
113}
114
jbauch095ae152015-12-18 01:39:55 -0800115PhysicalSocket::PhysicalSocket(PhysicalSocketServer* ss, SOCKET s)
jbauch577f5dc2017-05-17 16:32:26 -0700116 : ss_(ss), s_(s), error_(0),
jbauch095ae152015-12-18 01:39:55 -0800117 state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED),
118 resolver_(nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000119#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800120 // EnsureWinsockInit() ensures that winsock is initialized. The default
121 // version of this function doesn't do anything because winsock is
122 // initialized by constructor of a static object. If neccessary libjingle
123 // users can link it with a different version of this function by replacing
124 // win32socketinit.cc. See win32socketinit.cc for more details.
125 EnsureWinsockInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000126#endif
jbauch095ae152015-12-18 01:39:55 -0800127 if (s_ != INVALID_SOCKET) {
jbauch577f5dc2017-05-17 16:32:26 -0700128 SetEnabledEvents(DE_READ | DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000129
jbauch095ae152015-12-18 01:39:55 -0800130 int type = SOCK_STREAM;
131 socklen_t len = sizeof(type);
nissec16fa5e2017-02-07 07:18:43 -0800132 const int res =
133 getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len);
134 RTC_DCHECK_EQ(0, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000135 udp_ = (SOCK_DGRAM == type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000136 }
jbauch095ae152015-12-18 01:39:55 -0800137}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000138
jbauch095ae152015-12-18 01:39:55 -0800139PhysicalSocket::~PhysicalSocket() {
140 Close();
141}
142
143bool PhysicalSocket::Create(int family, int type) {
144 Close();
145 s_ = ::socket(family, type, 0);
146 udp_ = (SOCK_DGRAM == type);
147 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700148 if (udp_) {
149 SetEnabledEvents(DE_READ | DE_WRITE);
150 }
jbauch095ae152015-12-18 01:39:55 -0800151 return s_ != INVALID_SOCKET;
152}
153
154SocketAddress PhysicalSocket::GetLocalAddress() const {
155 sockaddr_storage addr_storage = {0};
156 socklen_t addrlen = sizeof(addr_storage);
157 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
158 int result = ::getsockname(s_, addr, &addrlen);
159 SocketAddress address;
160 if (result >= 0) {
161 SocketAddressFromSockAddrStorage(addr_storage, &address);
162 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100163 RTC_LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
164 << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000165 }
jbauch095ae152015-12-18 01:39:55 -0800166 return address;
167}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000168
jbauch095ae152015-12-18 01:39:55 -0800169SocketAddress PhysicalSocket::GetRemoteAddress() const {
170 sockaddr_storage addr_storage = {0};
171 socklen_t addrlen = sizeof(addr_storage);
172 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
173 int result = ::getpeername(s_, addr, &addrlen);
174 SocketAddress address;
175 if (result >= 0) {
176 SocketAddressFromSockAddrStorage(addr_storage, &address);
177 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100178 RTC_LOG(LS_WARNING)
179 << "GetRemoteAddress: unable to get remote addr, socket=" << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000180 }
jbauch095ae152015-12-18 01:39:55 -0800181 return address;
182}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000183
jbauch095ae152015-12-18 01:39:55 -0800184int PhysicalSocket::Bind(const SocketAddress& bind_addr) {
deadbeefc874d122017-02-13 15:41:59 -0800185 SocketAddress copied_bind_addr = bind_addr;
186 // If a network binder is available, use it to bind a socket to an interface
187 // instead of bind(), since this is more reliable on an OS with a weak host
188 // model.
deadbeef9ffa13f2017-02-21 16:18:00 -0800189 if (ss_->network_binder() && !bind_addr.IsAnyIP()) {
deadbeefc874d122017-02-13 15:41:59 -0800190 NetworkBindingResult result =
191 ss_->network_binder()->BindSocketToNetwork(s_, bind_addr.ipaddr());
192 if (result == NetworkBindingResult::SUCCESS) {
193 // Since the network binder handled binding the socket to the desired
194 // network interface, we don't need to (and shouldn't) include an IP in
195 // the bind() call; bind() just needs to assign a port.
196 copied_bind_addr.SetIP(GetAnyIP(copied_bind_addr.ipaddr().family()));
197 } else if (result == NetworkBindingResult::NOT_IMPLEMENTED) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100198 RTC_LOG(LS_INFO) << "Can't bind socket to network because "
199 "network binding is not implemented for this OS.";
deadbeefc874d122017-02-13 15:41:59 -0800200 } else {
201 if (bind_addr.IsLoopbackIP()) {
202 // If we couldn't bind to a loopback IP (which should only happen in
203 // test scenarios), continue on. This may be expected behavior.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100204 RTC_LOG(LS_VERBOSE) << "Binding socket to loopback address "
205 << bind_addr.ipaddr().ToString()
206 << " failed; result: " << static_cast<int>(result);
deadbeefc874d122017-02-13 15:41:59 -0800207 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100208 RTC_LOG(LS_WARNING) << "Binding socket to network address "
209 << bind_addr.ipaddr().ToString()
210 << " failed; result: " << static_cast<int>(result);
deadbeefc874d122017-02-13 15:41:59 -0800211 // If a network binding was attempted and failed, we should stop here
212 // and not try to use the socket. Otherwise, we may end up sending
213 // packets with an invalid source address.
214 // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=7026
215 return -1;
216 }
217 }
218 }
jbauch095ae152015-12-18 01:39:55 -0800219 sockaddr_storage addr_storage;
deadbeefc874d122017-02-13 15:41:59 -0800220 size_t len = copied_bind_addr.ToSockAddrStorage(&addr_storage);
jbauch095ae152015-12-18 01:39:55 -0800221 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
222 int err = ::bind(s_, addr, static_cast<int>(len));
223 UpdateLastError();
tfarinaa41ab932015-10-30 16:08:48 -0700224#if !defined(NDEBUG)
jbauch095ae152015-12-18 01:39:55 -0800225 if (0 == err) {
226 dbg_addr_ = "Bound @ ";
227 dbg_addr_.append(GetLocalAddress().ToString());
228 }
tfarinaa41ab932015-10-30 16:08:48 -0700229#endif
jbauch095ae152015-12-18 01:39:55 -0800230 return err;
231}
232
233int PhysicalSocket::Connect(const SocketAddress& addr) {
234 // TODO(pthatcher): Implicit creation is required to reconnect...
235 // ...but should we make it more explicit?
236 if (state_ != CS_CLOSED) {
237 SetError(EALREADY);
238 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000239 }
jbauch095ae152015-12-18 01:39:55 -0800240 if (addr.IsUnresolvedIP()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100241 RTC_LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
jbauch095ae152015-12-18 01:39:55 -0800242 resolver_ = new AsyncResolver();
243 resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult);
244 resolver_->Start(addr);
245 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000246 return 0;
247 }
248
jbauch095ae152015-12-18 01:39:55 -0800249 return DoConnect(addr);
250}
251
252int PhysicalSocket::DoConnect(const SocketAddress& connect_addr) {
253 if ((s_ == INVALID_SOCKET) &&
254 !Create(connect_addr.family(), SOCK_STREAM)) {
255 return SOCKET_ERROR;
256 }
257 sockaddr_storage addr_storage;
258 size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
259 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
260 int err = ::connect(s_, addr, static_cast<int>(len));
261 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700262 uint8_t events = DE_READ | DE_WRITE;
jbauch095ae152015-12-18 01:39:55 -0800263 if (err == 0) {
264 state_ = CS_CONNECTED;
265 } else if (IsBlockingError(GetError())) {
266 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700267 events |= DE_CONNECT;
jbauch095ae152015-12-18 01:39:55 -0800268 } else {
269 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000270 }
271
jbauch577f5dc2017-05-17 16:32:26 -0700272 EnableEvents(events);
jbauch095ae152015-12-18 01:39:55 -0800273 return 0;
274}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000275
jbauch095ae152015-12-18 01:39:55 -0800276int PhysicalSocket::GetError() const {
277 CritScope cs(&crit_);
278 return error_;
279}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000280
jbauch095ae152015-12-18 01:39:55 -0800281void PhysicalSocket::SetError(int error) {
282 CritScope cs(&crit_);
283 error_ = error;
284}
285
286AsyncSocket::ConnState PhysicalSocket::GetState() const {
287 return state_;
288}
289
290int PhysicalSocket::GetOption(Option opt, int* value) {
291 int slevel;
292 int sopt;
293 if (TranslateOption(opt, &slevel, &sopt) == -1)
294 return -1;
295 socklen_t optlen = sizeof(*value);
296 int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
297 if (ret != -1 && opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000298#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800299 *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000300#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000301 }
jbauch095ae152015-12-18 01:39:55 -0800302 return ret;
303}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000304
jbauch095ae152015-12-18 01:39:55 -0800305int PhysicalSocket::SetOption(Option opt, int value) {
306 int slevel;
307 int sopt;
308 if (TranslateOption(opt, &slevel, &sopt) == -1)
309 return -1;
310 if (opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000311#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800312 value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000313#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000314 }
jbauch095ae152015-12-18 01:39:55 -0800315 return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
316}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000317
jbauch095ae152015-12-18 01:39:55 -0800318int PhysicalSocket::Send(const void* pv, size_t cb) {
jbauchf2a2bf42016-02-03 16:45:32 -0800319 int sent = DoSend(s_, reinterpret_cast<const char *>(pv),
320 static_cast<int>(cb),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000321#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800322 // Suppress SIGPIPE. Without this, attempting to send on a socket whose
323 // other end is closed will result in a SIGPIPE signal being raised to
324 // our process, which by default will terminate the process, which we
325 // don't want. By specifying this flag, we'll just get the error EPIPE
326 // instead and can handle the error gracefully.
327 MSG_NOSIGNAL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000328#else
jbauch095ae152015-12-18 01:39:55 -0800329 0
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000330#endif
jbauch095ae152015-12-18 01:39:55 -0800331 );
332 UpdateLastError();
333 MaybeRemapSendError();
334 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800335 RTC_DCHECK(sent <= static_cast<int>(cb));
jbauchf2a2bf42016-02-03 16:45:32 -0800336 if ((sent > 0 && sent < static_cast<int>(cb)) ||
337 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700338 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000339 }
jbauch095ae152015-12-18 01:39:55 -0800340 return sent;
341}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000342
jbauch095ae152015-12-18 01:39:55 -0800343int PhysicalSocket::SendTo(const void* buffer,
344 size_t length,
345 const SocketAddress& addr) {
346 sockaddr_storage saddr;
347 size_t len = addr.ToSockAddrStorage(&saddr);
jbauchf2a2bf42016-02-03 16:45:32 -0800348 int sent = DoSendTo(
jbauch095ae152015-12-18 01:39:55 -0800349 s_, static_cast<const char *>(buffer), static_cast<int>(length),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000350#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800351 // Suppress SIGPIPE. See above for explanation.
352 MSG_NOSIGNAL,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000353#else
jbauch095ae152015-12-18 01:39:55 -0800354 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000355#endif
jbauch095ae152015-12-18 01:39:55 -0800356 reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
357 UpdateLastError();
358 MaybeRemapSendError();
359 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800360 RTC_DCHECK(sent <= static_cast<int>(length));
jbauchf2a2bf42016-02-03 16:45:32 -0800361 if ((sent > 0 && sent < static_cast<int>(length)) ||
362 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700363 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000364 }
jbauch095ae152015-12-18 01:39:55 -0800365 return sent;
366}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000367
Stefan Holmer9131efd2016-05-23 18:19:26 +0200368int PhysicalSocket::Recv(void* buffer, size_t length, int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800369 int received = ::recv(s_, static_cast<char*>(buffer),
370 static_cast<int>(length), 0);
371 if ((received == 0) && (length != 0)) {
372 // Note: on graceful shutdown, recv can return 0. In this case, we
373 // pretend it is blocking, and then signal close, so that simplifying
374 // assumptions can be made about Recv.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100375 RTC_LOG(LS_WARNING) << "EOF from socket; deferring close event";
jbauch095ae152015-12-18 01:39:55 -0800376 // Must turn this back on so that the select() loop will notice the close
377 // event.
jbauch577f5dc2017-05-17 16:32:26 -0700378 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800379 SetError(EWOULDBLOCK);
380 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000381 }
Stefan Holmer9131efd2016-05-23 18:19:26 +0200382 if (timestamp) {
383 *timestamp = GetSocketRecvTimestamp(s_);
384 }
jbauch095ae152015-12-18 01:39:55 -0800385 UpdateLastError();
386 int error = GetError();
387 bool success = (received >= 0) || IsBlockingError(error);
388 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700389 EnableEvents(DE_READ);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000390 }
jbauch095ae152015-12-18 01:39:55 -0800391 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100392 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000393 }
jbauch095ae152015-12-18 01:39:55 -0800394 return received;
395}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000396
jbauch095ae152015-12-18 01:39:55 -0800397int PhysicalSocket::RecvFrom(void* buffer,
398 size_t length,
Stefan Holmer9131efd2016-05-23 18:19:26 +0200399 SocketAddress* out_addr,
400 int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800401 sockaddr_storage addr_storage;
402 socklen_t addr_len = sizeof(addr_storage);
403 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
404 int received = ::recvfrom(s_, static_cast<char*>(buffer),
405 static_cast<int>(length), 0, addr, &addr_len);
Stefan Holmer9131efd2016-05-23 18:19:26 +0200406 if (timestamp) {
407 *timestamp = GetSocketRecvTimestamp(s_);
408 }
jbauch095ae152015-12-18 01:39:55 -0800409 UpdateLastError();
410 if ((received >= 0) && (out_addr != nullptr))
411 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
412 int error = GetError();
413 bool success = (received >= 0) || IsBlockingError(error);
414 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700415 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800416 }
417 if (!success) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100418 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
jbauch095ae152015-12-18 01:39:55 -0800419 }
420 return received;
421}
422
423int PhysicalSocket::Listen(int backlog) {
424 int err = ::listen(s_, backlog);
425 UpdateLastError();
426 if (err == 0) {
427 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700428 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800429#if !defined(NDEBUG)
430 dbg_addr_ = "Listening @ ";
431 dbg_addr_.append(GetLocalAddress().ToString());
432#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000433 }
jbauch095ae152015-12-18 01:39:55 -0800434 return err;
435}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000436
jbauch095ae152015-12-18 01:39:55 -0800437AsyncSocket* PhysicalSocket::Accept(SocketAddress* out_addr) {
438 // Always re-subscribe DE_ACCEPT to make sure new incoming connections will
439 // trigger an event even if DoAccept returns an error here.
jbauch577f5dc2017-05-17 16:32:26 -0700440 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800441 sockaddr_storage addr_storage;
442 socklen_t addr_len = sizeof(addr_storage);
443 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
444 SOCKET s = DoAccept(s_, addr, &addr_len);
445 UpdateLastError();
446 if (s == INVALID_SOCKET)
447 return nullptr;
448 if (out_addr != nullptr)
449 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
450 return ss_->WrapSocket(s);
451}
452
453int PhysicalSocket::Close() {
454 if (s_ == INVALID_SOCKET)
455 return 0;
456 int err = ::closesocket(s_);
457 UpdateLastError();
458 s_ = INVALID_SOCKET;
459 state_ = CS_CLOSED;
jbauch577f5dc2017-05-17 16:32:26 -0700460 SetEnabledEvents(0);
jbauch095ae152015-12-18 01:39:55 -0800461 if (resolver_) {
462 resolver_->Destroy(false);
463 resolver_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000464 }
jbauch095ae152015-12-18 01:39:55 -0800465 return err;
466}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000467
jbauch095ae152015-12-18 01:39:55 -0800468SOCKET PhysicalSocket::DoAccept(SOCKET socket,
469 sockaddr* addr,
470 socklen_t* addrlen) {
471 return ::accept(socket, addr, addrlen);
472}
473
jbauchf2a2bf42016-02-03 16:45:32 -0800474int PhysicalSocket::DoSend(SOCKET socket, const char* buf, int len, int flags) {
475 return ::send(socket, buf, len, flags);
476}
477
478int PhysicalSocket::DoSendTo(SOCKET socket,
479 const char* buf,
480 int len,
481 int flags,
482 const struct sockaddr* dest_addr,
483 socklen_t addrlen) {
484 return ::sendto(socket, buf, len, flags, dest_addr, addrlen);
485}
486
jbauch095ae152015-12-18 01:39:55 -0800487void PhysicalSocket::OnResolveResult(AsyncResolverInterface* resolver) {
488 if (resolver != resolver_) {
489 return;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000490 }
491
jbauch095ae152015-12-18 01:39:55 -0800492 int error = resolver_->GetError();
493 if (error == 0) {
494 error = DoConnect(resolver_->address());
495 } else {
496 Close();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000497 }
498
jbauch095ae152015-12-18 01:39:55 -0800499 if (error) {
500 SetError(error);
501 SignalCloseEvent(this, error);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000502 }
jbauch095ae152015-12-18 01:39:55 -0800503}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000504
jbauch095ae152015-12-18 01:39:55 -0800505void PhysicalSocket::UpdateLastError() {
Patrik Höglunda8005cf2017-12-13 16:05:42 +0100506 SetError(LAST_SYSTEM_ERROR);
jbauch095ae152015-12-18 01:39:55 -0800507}
508
509void PhysicalSocket::MaybeRemapSendError() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000510#if defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800511 // https://developer.apple.com/library/mac/documentation/Darwin/
512 // Reference/ManPages/man2/sendto.2.html
513 // ENOBUFS - The output queue for a network interface is full.
514 // This generally indicates that the interface has stopped sending,
515 // but may be caused by transient congestion.
516 if (GetError() == ENOBUFS) {
517 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000518 }
jbauch095ae152015-12-18 01:39:55 -0800519#endif
520}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000521
jbauch577f5dc2017-05-17 16:32:26 -0700522void PhysicalSocket::SetEnabledEvents(uint8_t events) {
523 enabled_events_ = events;
524}
525
526void PhysicalSocket::EnableEvents(uint8_t events) {
527 enabled_events_ |= events;
528}
529
530void PhysicalSocket::DisableEvents(uint8_t events) {
531 enabled_events_ &= ~events;
532}
533
jbauch095ae152015-12-18 01:39:55 -0800534int PhysicalSocket::TranslateOption(Option opt, int* slevel, int* sopt) {
535 switch (opt) {
536 case OPT_DONTFRAGMENT:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000537#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800538 *slevel = IPPROTO_IP;
539 *sopt = IP_DONTFRAGMENT;
540 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000541#elif defined(WEBRTC_MAC) || defined(BSD) || defined(__native_client__)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100542 RTC_LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
jbauch095ae152015-12-18 01:39:55 -0800543 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000544#elif defined(WEBRTC_POSIX)
jbauch095ae152015-12-18 01:39:55 -0800545 *slevel = IPPROTO_IP;
546 *sopt = IP_MTU_DISCOVER;
547 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000548#endif
jbauch095ae152015-12-18 01:39:55 -0800549 case OPT_RCVBUF:
550 *slevel = SOL_SOCKET;
551 *sopt = SO_RCVBUF;
552 break;
553 case OPT_SNDBUF:
554 *slevel = SOL_SOCKET;
555 *sopt = SO_SNDBUF;
556 break;
557 case OPT_NODELAY:
558 *slevel = IPPROTO_TCP;
559 *sopt = TCP_NODELAY;
560 break;
561 case OPT_DSCP:
Mirko Bonadei675513b2017-11-09 11:09:25 +0100562 RTC_LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
jbauch095ae152015-12-18 01:39:55 -0800563 return -1;
564 case OPT_RTP_SENDTIME_EXTN_ID:
565 return -1; // No logging is necessary as this not a OS socket option.
566 default:
nissec80e7412017-01-11 05:56:46 -0800567 RTC_NOTREACHED();
jbauch095ae152015-12-18 01:39:55 -0800568 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000569 }
jbauch095ae152015-12-18 01:39:55 -0800570 return 0;
571}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000572
jbauch4331fcd2016-01-06 22:20:28 -0800573SocketDispatcher::SocketDispatcher(PhysicalSocketServer *ss)
574#if defined(WEBRTC_WIN)
575 : PhysicalSocket(ss), id_(0), signal_close_(false)
576#else
577 : PhysicalSocket(ss)
578#endif
579{
580}
581
582SocketDispatcher::SocketDispatcher(SOCKET s, PhysicalSocketServer *ss)
583#if defined(WEBRTC_WIN)
584 : PhysicalSocket(ss, s), id_(0), signal_close_(false)
585#else
586 : PhysicalSocket(ss, s)
587#endif
588{
589}
590
591SocketDispatcher::~SocketDispatcher() {
592 Close();
593}
594
595bool SocketDispatcher::Initialize() {
nisseede5da42017-01-12 05:15:36 -0800596 RTC_DCHECK(s_ != INVALID_SOCKET);
jbauch4331fcd2016-01-06 22:20:28 -0800597 // Must be a non-blocking
598#if defined(WEBRTC_WIN)
599 u_long argp = 1;
600 ioctlsocket(s_, FIONBIO, &argp);
601#elif defined(WEBRTC_POSIX)
602 fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
603#endif
deadbeefeae45642017-05-26 16:27:09 -0700604#if defined(WEBRTC_IOS)
605 // iOS may kill sockets when the app is moved to the background
606 // (specifically, if the app doesn't use the "voip" UIBackgroundMode). When
607 // we attempt to write to such a socket, SIGPIPE will be raised, which by
608 // default will terminate the process, which we don't want. By specifying
609 // this socket option, SIGPIPE will be disabled for the socket.
610 int value = 1;
611 ::setsockopt(s_, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value));
612#endif
jbauch4331fcd2016-01-06 22:20:28 -0800613 ss_->Add(this);
614 return true;
615}
616
617bool SocketDispatcher::Create(int type) {
618 return Create(AF_INET, type);
619}
620
621bool SocketDispatcher::Create(int family, int type) {
622 // Change the socket to be non-blocking.
623 if (!PhysicalSocket::Create(family, type))
624 return false;
625
626 if (!Initialize())
627 return false;
628
629#if defined(WEBRTC_WIN)
630 do { id_ = ++next_id_; } while (id_ == 0);
631#endif
632 return true;
633}
634
635#if defined(WEBRTC_WIN)
636
637WSAEVENT SocketDispatcher::GetWSAEvent() {
638 return WSA_INVALID_EVENT;
639}
640
641SOCKET SocketDispatcher::GetSocket() {
642 return s_;
643}
644
645bool SocketDispatcher::CheckSignalClose() {
646 if (!signal_close_)
647 return false;
648
649 char ch;
650 if (recv(s_, &ch, 1, MSG_PEEK) > 0)
651 return false;
652
653 state_ = CS_CLOSED;
654 signal_close_ = false;
655 SignalCloseEvent(this, signal_err_);
656 return true;
657}
658
659int SocketDispatcher::next_id_ = 0;
660
661#elif defined(WEBRTC_POSIX)
662
663int SocketDispatcher::GetDescriptor() {
664 return s_;
665}
666
667bool SocketDispatcher::IsDescriptorClosed() {
deadbeeffaedf7f2017-02-09 15:09:22 -0800668 if (udp_) {
669 // The MSG_PEEK trick doesn't work for UDP, since (at least in some
670 // circumstances) it requires reading an entire UDP packet, which would be
671 // bad for performance here. So, just check whether |s_| has been closed,
672 // which should be sufficient.
673 return s_ == INVALID_SOCKET;
674 }
jbauch4331fcd2016-01-06 22:20:28 -0800675 // We don't have a reliable way of distinguishing end-of-stream
676 // from readability. So test on each readable call. Is this
677 // inefficient? Probably.
678 char ch;
679 ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
680 if (res > 0) {
681 // Data available, so not closed.
682 return false;
683 } else if (res == 0) {
684 // EOF, so closed.
685 return true;
686 } else { // error
687 switch (errno) {
688 // Returned if we've already closed s_.
689 case EBADF:
690 // Returned during ungraceful peer shutdown.
691 case ECONNRESET:
692 return true;
deadbeeffaedf7f2017-02-09 15:09:22 -0800693 // The normal blocking error; don't log anything.
694 case EWOULDBLOCK:
695 // Interrupted system call.
696 case EINTR:
697 return false;
jbauch4331fcd2016-01-06 22:20:28 -0800698 default:
699 // Assume that all other errors are just blocking errors, meaning the
700 // connection is still good but we just can't read from it right now.
701 // This should only happen when connecting (and at most once), because
702 // in all other cases this function is only called if the file
703 // descriptor is already known to be in the readable state. However,
704 // it's not necessary a problem if we spuriously interpret a
705 // "connection lost"-type error as a blocking error, because typically
706 // the next recv() will get EOF, so we'll still eventually notice that
707 // the socket is closed.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100708 RTC_LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
jbauch4331fcd2016-01-06 22:20:28 -0800709 return false;
710 }
711 }
712}
713
714#endif // WEBRTC_POSIX
715
716uint32_t SocketDispatcher::GetRequestedEvents() {
jbauch577f5dc2017-05-17 16:32:26 -0700717 return enabled_events();
jbauch4331fcd2016-01-06 22:20:28 -0800718}
719
720void SocketDispatcher::OnPreEvent(uint32_t ff) {
721 if ((ff & DE_CONNECT) != 0)
722 state_ = CS_CONNECTED;
723
724#if defined(WEBRTC_WIN)
725 // We set CS_CLOSED from CheckSignalClose.
726#elif defined(WEBRTC_POSIX)
727 if ((ff & DE_CLOSE) != 0)
728 state_ = CS_CLOSED;
729#endif
730}
731
732#if defined(WEBRTC_WIN)
733
734void SocketDispatcher::OnEvent(uint32_t ff, int err) {
735 int cache_id = id_;
736 // Make sure we deliver connect/accept first. Otherwise, consumers may see
737 // something like a READ followed by a CONNECT, which would be odd.
738 if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
739 if (ff != DE_CONNECT)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100740 RTC_LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
jbauch577f5dc2017-05-17 16:32:26 -0700741 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800742#if !defined(NDEBUG)
743 dbg_addr_ = "Connected @ ";
744 dbg_addr_.append(GetRemoteAddress().ToString());
745#endif
746 SignalConnectEvent(this);
747 }
748 if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700749 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800750 SignalReadEvent(this);
751 }
752 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700753 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800754 SignalReadEvent(this);
755 }
756 if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700757 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800758 SignalWriteEvent(this);
759 }
760 if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
761 signal_close_ = true;
762 signal_err_ = err;
763 }
764}
765
766#elif defined(WEBRTC_POSIX)
767
768void SocketDispatcher::OnEvent(uint32_t ff, int err) {
jbauchde4db112017-05-31 13:09:18 -0700769#if defined(WEBRTC_USE_EPOLL)
770 // Remember currently enabled events so we can combine multiple changes
771 // into one update call later.
772 // The signal handlers might re-enable events disabled here, so we can't
773 // keep a list of events to disable at the end of the method. This list
774 // would not be updated with the events enabled by the signal handlers.
775 StartBatchedEventUpdates();
776#endif
jbauch4331fcd2016-01-06 22:20:28 -0800777 // Make sure we deliver connect/accept first. Otherwise, consumers may see
778 // something like a READ followed by a CONNECT, which would be odd.
779 if ((ff & DE_CONNECT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700780 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800781 SignalConnectEvent(this);
782 }
783 if ((ff & DE_ACCEPT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700784 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800785 SignalReadEvent(this);
786 }
787 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700788 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800789 SignalReadEvent(this);
790 }
791 if ((ff & DE_WRITE) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700792 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800793 SignalWriteEvent(this);
794 }
795 if ((ff & DE_CLOSE) != 0) {
796 // The socket is now dead to us, so stop checking it.
jbauch577f5dc2017-05-17 16:32:26 -0700797 SetEnabledEvents(0);
jbauch4331fcd2016-01-06 22:20:28 -0800798 SignalCloseEvent(this, err);
799 }
jbauchde4db112017-05-31 13:09:18 -0700800#if defined(WEBRTC_USE_EPOLL)
801 FinishBatchedEventUpdates();
802#endif
jbauch4331fcd2016-01-06 22:20:28 -0800803}
804
805#endif // WEBRTC_POSIX
806
jbauchde4db112017-05-31 13:09:18 -0700807#if defined(WEBRTC_USE_EPOLL)
808
809static int GetEpollEvents(uint32_t ff) {
810 int events = 0;
811 if (ff & (DE_READ | DE_ACCEPT)) {
812 events |= EPOLLIN;
813 }
814 if (ff & (DE_WRITE | DE_CONNECT)) {
815 events |= EPOLLOUT;
816 }
817 return events;
818}
819
820void SocketDispatcher::StartBatchedEventUpdates() {
821 RTC_DCHECK_EQ(saved_enabled_events_, -1);
822 saved_enabled_events_ = enabled_events();
823}
824
825void SocketDispatcher::FinishBatchedEventUpdates() {
826 RTC_DCHECK_NE(saved_enabled_events_, -1);
827 uint8_t old_events = static_cast<uint8_t>(saved_enabled_events_);
828 saved_enabled_events_ = -1;
829 MaybeUpdateDispatcher(old_events);
830}
831
832void SocketDispatcher::MaybeUpdateDispatcher(uint8_t old_events) {
833 if (GetEpollEvents(enabled_events()) != GetEpollEvents(old_events) &&
834 saved_enabled_events_ == -1) {
835 ss_->Update(this);
836 }
837}
838
839void SocketDispatcher::SetEnabledEvents(uint8_t events) {
840 uint8_t old_events = enabled_events();
841 PhysicalSocket::SetEnabledEvents(events);
842 MaybeUpdateDispatcher(old_events);
843}
844
845void SocketDispatcher::EnableEvents(uint8_t events) {
846 uint8_t old_events = enabled_events();
847 PhysicalSocket::EnableEvents(events);
848 MaybeUpdateDispatcher(old_events);
849}
850
851void SocketDispatcher::DisableEvents(uint8_t events) {
852 uint8_t old_events = enabled_events();
853 PhysicalSocket::DisableEvents(events);
854 MaybeUpdateDispatcher(old_events);
855}
856
857#endif // WEBRTC_USE_EPOLL
858
jbauch4331fcd2016-01-06 22:20:28 -0800859int SocketDispatcher::Close() {
860 if (s_ == INVALID_SOCKET)
861 return 0;
862
863#if defined(WEBRTC_WIN)
864 id_ = 0;
865 signal_close_ = false;
866#endif
867 ss_->Remove(this);
868 return PhysicalSocket::Close();
869}
870
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000871#if defined(WEBRTC_POSIX)
872class EventDispatcher : public Dispatcher {
873 public:
874 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
875 if (pipe(afd_) < 0)
Mirko Bonadei675513b2017-11-09 11:09:25 +0100876 RTC_LOG(LERROR) << "pipe failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000877 ss_->Add(this);
878 }
879
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000880 ~EventDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000881 ss_->Remove(this);
882 close(afd_[0]);
883 close(afd_[1]);
884 }
885
886 virtual void Signal() {
887 CritScope cs(&crit_);
888 if (!fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200889 const uint8_t b[1] = {0};
nissec16fa5e2017-02-07 07:18:43 -0800890 const ssize_t res = write(afd_[1], b, sizeof(b));
891 RTC_DCHECK_EQ(1, res);
892 fSignaled_ = true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000893 }
894 }
895
Peter Boström0c4e06b2015-10-07 12:23:21 +0200896 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000897
Peter Boström0c4e06b2015-10-07 12:23:21 +0200898 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000899 // It is not possible to perfectly emulate an auto-resetting event with
900 // pipes. This simulates it by resetting before the event is handled.
901
902 CritScope cs(&crit_);
903 if (fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200904 uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
nissec16fa5e2017-02-07 07:18:43 -0800905 const ssize_t res = read(afd_[0], b, sizeof(b));
906 RTC_DCHECK_EQ(1, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000907 fSignaled_ = false;
908 }
909 }
910
nissec80e7412017-01-11 05:56:46 -0800911 void OnEvent(uint32_t ff, int err) override { RTC_NOTREACHED(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000912
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000913 int GetDescriptor() override { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000914
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000915 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000916
917 private:
918 PhysicalSocketServer *ss_;
919 int afd_[2];
920 bool fSignaled_;
921 CriticalSection crit_;
922};
923
924// These two classes use the self-pipe trick to deliver POSIX signals to our
925// select loop. This is the only safe, reliable, cross-platform way to do
926// non-trivial things with a POSIX signal in an event-driven program (until
927// proper pselect() implementations become ubiquitous).
928
929class PosixSignalHandler {
930 public:
931 // POSIX only specifies 32 signals, but in principle the system might have
932 // more and the programmer might choose to use them, so we size our array
933 // for 128.
934 static const int kNumPosixSignals = 128;
935
936 // There is just a single global instance. (Signal handlers do not get any
937 // sort of user-defined void * parameter, so they can't access anything that
938 // isn't global.)
939 static PosixSignalHandler* Instance() {
Niels Möller14682a32018-05-24 08:54:25 +0200940 static PosixSignalHandler* const instance = new PosixSignalHandler();
941 return instance;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000942 }
943
944 // Returns true if the given signal number is set.
945 bool IsSignalSet(int signum) const {
nisseede5da42017-01-12 05:15:36 -0800946 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800947 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000948 return received_signal_[signum];
949 } else {
950 return false;
951 }
952 }
953
954 // Clears the given signal number.
955 void ClearSignal(int signum) {
nisseede5da42017-01-12 05:15:36 -0800956 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800957 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000958 received_signal_[signum] = false;
959 }
960 }
961
962 // Returns the file descriptor to monitor for signal events.
963 int GetDescriptor() const {
964 return afd_[0];
965 }
966
967 // This is called directly from our real signal handler, so it must be
968 // signal-handler-safe. That means it cannot assume anything about the
969 // user-level state of the process, since the handler could be executed at any
970 // time on any thread.
971 void OnPosixSignalReceived(int signum) {
tfarina5237aaf2015-11-10 23:44:30 -0800972 if (signum >= static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000973 // We don't have space in our array for this.
974 return;
975 }
976 // Set a flag saying we've seen this signal.
977 received_signal_[signum] = true;
978 // Notify application code that we got a signal.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200979 const uint8_t b[1] = {0};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000980 if (-1 == write(afd_[1], b, sizeof(b))) {
981 // Nothing we can do here. If there's an error somehow then there's
982 // nothing we can safely do from a signal handler.
983 // No, we can't even safely log it.
984 // But, we still have to check the return value here. Otherwise,
985 // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
986 return;
987 }
988 }
989
990 private:
991 PosixSignalHandler() {
992 if (pipe(afd_) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100993 RTC_LOG_ERR(LS_ERROR) << "pipe failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000994 return;
995 }
996 if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100997 RTC_LOG_ERR(LS_WARNING) << "fcntl #1 failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000998 }
999 if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001000 RTC_LOG_ERR(LS_WARNING) << "fcntl #2 failed";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001001 }
1002 memset(const_cast<void *>(static_cast<volatile void *>(received_signal_)),
1003 0,
1004 sizeof(received_signal_));
1005 }
1006
1007 ~PosixSignalHandler() {
1008 int fd1 = afd_[0];
1009 int fd2 = afd_[1];
1010 // We clobber the stored file descriptor numbers here or else in principle
1011 // a signal that happens to be delivered during application termination
1012 // could erroneously write a zero byte to an unrelated file handle in
1013 // OnPosixSignalReceived() if some other file happens to be opened later
1014 // during shutdown and happens to be given the same file descriptor number
1015 // as our pipe had. Unfortunately even with this precaution there is still a
1016 // race where that could occur if said signal happens to be handled
1017 // concurrently with this code and happens to have already read the value of
1018 // afd_[1] from memory before we clobber it, but that's unlikely.
1019 afd_[0] = -1;
1020 afd_[1] = -1;
1021 close(fd1);
1022 close(fd2);
1023 }
1024
1025 int afd_[2];
1026 // These are boolean flags that will be set in our signal handler and read
1027 // and cleared from Wait(). There is a race involved in this, but it is
1028 // benign. The signal handler sets the flag before signaling the pipe, so
1029 // we'll never end up blocking in select() while a flag is still true.
1030 // However, if two of the same signal arrive close to each other then it's
1031 // possible that the second time the handler may set the flag while it's still
1032 // true, meaning that signal will be missed. But the first occurrence of it
1033 // will still be handled, so this isn't a problem.
1034 // Volatile is not necessary here for correctness, but this data _is_ volatile
1035 // so I've marked it as such.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001036 volatile uint8_t received_signal_[kNumPosixSignals];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001037};
1038
1039class PosixSignalDispatcher : public Dispatcher {
1040 public:
1041 PosixSignalDispatcher(PhysicalSocketServer *owner) : owner_(owner) {
1042 owner_->Add(this);
1043 }
1044
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001045 ~PosixSignalDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001046 owner_->Remove(this);
1047 }
1048
Peter Boström0c4e06b2015-10-07 12:23:21 +02001049 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001050
Peter Boström0c4e06b2015-10-07 12:23:21 +02001051 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001052 // Events might get grouped if signals come very fast, so we read out up to
1053 // 16 bytes to make sure we keep the pipe empty.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001054 uint8_t b[16];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001055 ssize_t ret = read(GetDescriptor(), b, sizeof(b));
1056 if (ret < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001057 RTC_LOG_ERR(LS_WARNING) << "Error in read()";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001058 } else if (ret == 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001059 RTC_LOG(LS_WARNING) << "Should have read at least one byte";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001060 }
1061 }
1062
Peter Boström0c4e06b2015-10-07 12:23:21 +02001063 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001064 for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
1065 ++signum) {
1066 if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
1067 PosixSignalHandler::Instance()->ClearSignal(signum);
1068 HandlerMap::iterator i = handlers_.find(signum);
1069 if (i == handlers_.end()) {
1070 // This can happen if a signal is delivered to our process at around
1071 // the same time as we unset our handler for it. It is not an error
1072 // condition, but it's unusual enough to be worth logging.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001073 RTC_LOG(LS_INFO) << "Received signal with no handler: " << signum;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001074 } else {
1075 // Otherwise, execute our handler.
1076 (*i->second)(signum);
1077 }
1078 }
1079 }
1080 }
1081
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001082 int GetDescriptor() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001083 return PosixSignalHandler::Instance()->GetDescriptor();
1084 }
1085
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001086 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001087
1088 void SetHandler(int signum, void (*handler)(int)) {
1089 handlers_[signum] = handler;
1090 }
1091
1092 void ClearHandler(int signum) {
1093 handlers_.erase(signum);
1094 }
1095
1096 bool HasHandlers() {
1097 return !handlers_.empty();
1098 }
1099
1100 private:
1101 typedef std::map<int, void (*)(int)> HandlerMap;
1102
1103 HandlerMap handlers_;
1104 // Our owner.
1105 PhysicalSocketServer *owner_;
1106};
1107
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001108#endif // WEBRTC_POSIX
1109
1110#if defined(WEBRTC_WIN)
Peter Boström0c4e06b2015-10-07 12:23:21 +02001111static uint32_t FlagsToEvents(uint32_t events) {
1112 uint32_t ffFD = FD_CLOSE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001113 if (events & DE_READ)
1114 ffFD |= FD_READ;
1115 if (events & DE_WRITE)
1116 ffFD |= FD_WRITE;
1117 if (events & DE_CONNECT)
1118 ffFD |= FD_CONNECT;
1119 if (events & DE_ACCEPT)
1120 ffFD |= FD_ACCEPT;
1121 return ffFD;
1122}
1123
1124class EventDispatcher : public Dispatcher {
1125 public:
1126 EventDispatcher(PhysicalSocketServer *ss) : ss_(ss) {
1127 hev_ = WSACreateEvent();
1128 if (hev_) {
1129 ss_->Add(this);
1130 }
1131 }
1132
Steve Anton9de3aac2017-10-24 10:08:26 -07001133 ~EventDispatcher() override {
deadbeef37f5ecf2017-02-27 14:06:41 -08001134 if (hev_ != nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001135 ss_->Remove(this);
1136 WSACloseEvent(hev_);
deadbeef37f5ecf2017-02-27 14:06:41 -08001137 hev_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001138 }
1139 }
1140
1141 virtual void Signal() {
deadbeef37f5ecf2017-02-27 14:06:41 -08001142 if (hev_ != nullptr)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001143 WSASetEvent(hev_);
1144 }
1145
Steve Anton9de3aac2017-10-24 10:08:26 -07001146 uint32_t GetRequestedEvents() override { return 0; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001147
Steve Anton9de3aac2017-10-24 10:08:26 -07001148 void OnPreEvent(uint32_t ff) override { WSAResetEvent(hev_); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001149
Steve Anton9de3aac2017-10-24 10:08:26 -07001150 void OnEvent(uint32_t ff, int err) override {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001151
Steve Anton9de3aac2017-10-24 10:08:26 -07001152 WSAEVENT GetWSAEvent() override { return hev_; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001153
Steve Anton9de3aac2017-10-24 10:08:26 -07001154 SOCKET GetSocket() override { return INVALID_SOCKET; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001155
Steve Anton9de3aac2017-10-24 10:08:26 -07001156 bool CheckSignalClose() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001157
Steve Anton9de3aac2017-10-24 10:08:26 -07001158 private:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001159 PhysicalSocketServer* ss_;
1160 WSAEVENT hev_;
1161};
honghaizcec0a082016-01-15 14:49:09 -08001162#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001163
1164// Sets the value of a boolean value to false when signaled.
1165class Signaler : public EventDispatcher {
1166 public:
1167 Signaler(PhysicalSocketServer* ss, bool* pf)
1168 : EventDispatcher(ss), pf_(pf) {
1169 }
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001170 ~Signaler() override { }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001171
Peter Boström0c4e06b2015-10-07 12:23:21 +02001172 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001173 if (pf_)
1174 *pf_ = false;
1175 }
1176
1177 private:
1178 bool *pf_;
1179};
1180
1181PhysicalSocketServer::PhysicalSocketServer()
1182 : fWait_(false) {
jbauchde4db112017-05-31 13:09:18 -07001183#if defined(WEBRTC_USE_EPOLL)
1184 // Since Linux 2.6.8, the size argument is ignored, but must be greater than
1185 // zero. Before that the size served as hint to the kernel for the amount of
1186 // space to initially allocate in internal data structures.
1187 epoll_fd_ = epoll_create(FD_SETSIZE);
1188 if (epoll_fd_ == -1) {
1189 // Not an error, will fall back to "select" below.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001190 RTC_LOG_E(LS_WARNING, EN, errno) << "epoll_create";
jbauchde4db112017-05-31 13:09:18 -07001191 epoll_fd_ = INVALID_SOCKET;
1192 }
1193#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001194 signal_wakeup_ = new Signaler(this, &fWait_);
1195#if defined(WEBRTC_WIN)
1196 socket_ev_ = WSACreateEvent();
1197#endif
1198}
1199
1200PhysicalSocketServer::~PhysicalSocketServer() {
1201#if defined(WEBRTC_WIN)
1202 WSACloseEvent(socket_ev_);
1203#endif
1204#if defined(WEBRTC_POSIX)
1205 signal_dispatcher_.reset();
1206#endif
1207 delete signal_wakeup_;
jbauchde4db112017-05-31 13:09:18 -07001208#if defined(WEBRTC_USE_EPOLL)
1209 if (epoll_fd_ != INVALID_SOCKET) {
1210 close(epoll_fd_);
1211 }
1212#endif
nisseede5da42017-01-12 05:15:36 -08001213 RTC_DCHECK(dispatchers_.empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001214}
1215
1216void PhysicalSocketServer::WakeUp() {
1217 signal_wakeup_->Signal();
1218}
1219
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001220Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
1221 PhysicalSocket* socket = new PhysicalSocket(this);
1222 if (socket->Create(family, type)) {
1223 return socket;
1224 } else {
1225 delete socket;
jbauch095ae152015-12-18 01:39:55 -08001226 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001227 }
1228}
1229
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001230AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
1231 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1232 if (dispatcher->Create(family, type)) {
1233 return dispatcher;
1234 } else {
1235 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001236 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001237 }
1238}
1239
1240AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
1241 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1242 if (dispatcher->Initialize()) {
1243 return dispatcher;
1244 } else {
1245 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001246 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001247 }
1248}
1249
1250void PhysicalSocketServer::Add(Dispatcher *pdispatcher) {
1251 CritScope cs(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001252 if (processing_dispatchers_) {
1253 // A dispatcher is being added while a "Wait" call is processing the
1254 // list of socket events.
1255 // Defer adding to "dispatchers_" set until processing is done to avoid
1256 // invalidating the iterator in "Wait".
1257 pending_remove_dispatchers_.erase(pdispatcher);
1258 pending_add_dispatchers_.insert(pdispatcher);
1259 } else {
1260 dispatchers_.insert(pdispatcher);
1261 }
1262#if defined(WEBRTC_USE_EPOLL)
1263 if (epoll_fd_ != INVALID_SOCKET) {
1264 AddEpoll(pdispatcher);
1265 }
1266#endif // WEBRTC_USE_EPOLL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001267}
1268
1269void PhysicalSocketServer::Remove(Dispatcher *pdispatcher) {
1270 CritScope cs(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001271 if (processing_dispatchers_) {
1272 // A dispatcher is being removed while a "Wait" call is processing the
1273 // list of socket events.
1274 // Defer removal from "dispatchers_" set until processing is done to avoid
1275 // invalidating the iterator in "Wait".
1276 if (!pending_add_dispatchers_.erase(pdispatcher) &&
1277 dispatchers_.find(pdispatcher) == dispatchers_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001278 RTC_LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
1279 << "dispatcher, potentially from a duplicate call to "
1280 << "Add.";
jbauchde4db112017-05-31 13:09:18 -07001281 return;
1282 }
1283
1284 pending_remove_dispatchers_.insert(pdispatcher);
1285 } else if (!dispatchers_.erase(pdispatcher)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001286 RTC_LOG(LS_WARNING)
1287 << "PhysicalSocketServer asked to remove a unknown "
1288 << "dispatcher, potentially from a duplicate call to Add.";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001289 return;
1290 }
jbauchde4db112017-05-31 13:09:18 -07001291#if defined(WEBRTC_USE_EPOLL)
1292 if (epoll_fd_ != INVALID_SOCKET) {
1293 RemoveEpoll(pdispatcher);
1294 }
1295#endif // WEBRTC_USE_EPOLL
1296}
1297
1298void PhysicalSocketServer::Update(Dispatcher* pdispatcher) {
1299#if defined(WEBRTC_USE_EPOLL)
1300 if (epoll_fd_ == INVALID_SOCKET) {
1301 return;
1302 }
1303
1304 CritScope cs(&crit_);
1305 if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1306 return;
1307 }
1308
1309 UpdateEpoll(pdispatcher);
1310#endif
1311}
1312
1313void PhysicalSocketServer::AddRemovePendingDispatchers() {
1314 if (!pending_add_dispatchers_.empty()) {
1315 for (Dispatcher* pdispatcher : pending_add_dispatchers_) {
1316 dispatchers_.insert(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001317 }
jbauchde4db112017-05-31 13:09:18 -07001318 pending_add_dispatchers_.clear();
1319 }
1320
1321 if (!pending_remove_dispatchers_.empty()) {
1322 for (Dispatcher* pdispatcher : pending_remove_dispatchers_) {
1323 dispatchers_.erase(pdispatcher);
1324 }
1325 pending_remove_dispatchers_.clear();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001326 }
1327}
1328
1329#if defined(WEBRTC_POSIX)
jbauchde4db112017-05-31 13:09:18 -07001330
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001331bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
jbauchde4db112017-05-31 13:09:18 -07001332#if defined(WEBRTC_USE_EPOLL)
1333 // We don't keep a dedicated "epoll" descriptor containing only the non-IO
1334 // (i.e. signaling) dispatcher, so "poll" will be used instead of the default
1335 // "select" to support sockets larger than FD_SETSIZE.
1336 if (!process_io) {
1337 return WaitPoll(cmsWait, signal_wakeup_);
1338 } else if (epoll_fd_ != INVALID_SOCKET) {
1339 return WaitEpoll(cmsWait);
1340 }
1341#endif
1342 return WaitSelect(cmsWait, process_io);
1343}
1344
1345static void ProcessEvents(Dispatcher* dispatcher,
1346 bool readable,
1347 bool writable,
1348 bool check_error) {
1349 int errcode = 0;
1350 // TODO(pthatcher): Should we set errcode if getsockopt fails?
1351 if (check_error) {
1352 socklen_t len = sizeof(errcode);
1353 ::getsockopt(dispatcher->GetDescriptor(), SOL_SOCKET, SO_ERROR, &errcode,
1354 &len);
1355 }
1356
1357 uint32_t ff = 0;
1358
1359 // Check readable descriptors. If we're waiting on an accept, signal
1360 // that. Otherwise we're waiting for data, check to see if we're
1361 // readable or really closed.
1362 // TODO(pthatcher): Only peek at TCP descriptors.
1363 if (readable) {
1364 if (dispatcher->GetRequestedEvents() & DE_ACCEPT) {
1365 ff |= DE_ACCEPT;
1366 } else if (errcode || dispatcher->IsDescriptorClosed()) {
1367 ff |= DE_CLOSE;
1368 } else {
1369 ff |= DE_READ;
1370 }
1371 }
1372
1373 // Check writable descriptors. If we're waiting on a connect, detect
1374 // success versus failure by the reaped error code.
1375 if (writable) {
1376 if (dispatcher->GetRequestedEvents() & DE_CONNECT) {
1377 if (!errcode) {
1378 ff |= DE_CONNECT;
1379 } else {
1380 ff |= DE_CLOSE;
1381 }
1382 } else {
1383 ff |= DE_WRITE;
1384 }
1385 }
1386
1387 // Tell the descriptor about the event.
1388 if (ff != 0) {
1389 dispatcher->OnPreEvent(ff);
1390 dispatcher->OnEvent(ff, errcode);
1391 }
1392}
1393
1394bool PhysicalSocketServer::WaitSelect(int cmsWait, bool process_io) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001395 // Calculate timing information
1396
deadbeef37f5ecf2017-02-27 14:06:41 -08001397 struct timeval* ptvWait = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001398 struct timeval tvWait;
1399 struct timeval tvStop;
1400 if (cmsWait != kForever) {
1401 // Calculate wait timeval
1402 tvWait.tv_sec = cmsWait / 1000;
1403 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1404 ptvWait = &tvWait;
1405
1406 // Calculate when to return in a timeval
deadbeef37f5ecf2017-02-27 14:06:41 -08001407 gettimeofday(&tvStop, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001408 tvStop.tv_sec += tvWait.tv_sec;
1409 tvStop.tv_usec += tvWait.tv_usec;
1410 if (tvStop.tv_usec >= 1000000) {
1411 tvStop.tv_usec -= 1000000;
1412 tvStop.tv_sec += 1;
1413 }
1414 }
1415
1416 // Zero all fd_sets. Don't need to do this inside the loop since
1417 // select() zeros the descriptors not signaled
1418
1419 fd_set fdsRead;
1420 FD_ZERO(&fdsRead);
1421 fd_set fdsWrite;
1422 FD_ZERO(&fdsWrite);
pbos@webrtc.org27e58982014-10-07 17:56:53 +00001423 // Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1424 // inline assembly in FD_ZERO.
1425 // http://crbug.com/344505
1426#ifdef MEMORY_SANITIZER
1427 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1428 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1429#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001430
1431 fWait_ = true;
1432
1433 while (fWait_) {
1434 int fdmax = -1;
1435 {
1436 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001437 // TODO(jbauch): Support re-entrant waiting.
1438 RTC_DCHECK(!processing_dispatchers_);
1439 for (Dispatcher* pdispatcher : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001440 // Query dispatchers for read and write wait state
nisseede5da42017-01-12 05:15:36 -08001441 RTC_DCHECK(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001442 if (!process_io && (pdispatcher != signal_wakeup_))
1443 continue;
1444 int fd = pdispatcher->GetDescriptor();
jbauchde4db112017-05-31 13:09:18 -07001445 // "select"ing a file descriptor that is equal to or larger than
1446 // FD_SETSIZE will result in undefined behavior.
1447 RTC_DCHECK_LT(fd, FD_SETSIZE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001448 if (fd > fdmax)
1449 fdmax = fd;
1450
Peter Boström0c4e06b2015-10-07 12:23:21 +02001451 uint32_t ff = pdispatcher->GetRequestedEvents();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001452 if (ff & (DE_READ | DE_ACCEPT))
1453 FD_SET(fd, &fdsRead);
1454 if (ff & (DE_WRITE | DE_CONNECT))
1455 FD_SET(fd, &fdsWrite);
1456 }
1457 }
1458
1459 // Wait then call handlers as appropriate
1460 // < 0 means error
1461 // 0 means timeout
1462 // > 0 means count of descriptors ready
deadbeef37f5ecf2017-02-27 14:06:41 -08001463 int n = select(fdmax + 1, &fdsRead, &fdsWrite, nullptr, ptvWait);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001464
1465 // If error, return error.
1466 if (n < 0) {
1467 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001468 RTC_LOG_E(LS_ERROR, EN, errno) << "select";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001469 return false;
1470 }
1471 // Else ignore the error and keep going. If this EINTR was for one of the
1472 // signals managed by this PhysicalSocketServer, the
1473 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1474 // iteration.
1475 } else if (n == 0) {
1476 // If timeout, return success
1477 return true;
1478 } else {
1479 // We have signaled descriptors
1480 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001481 processing_dispatchers_ = true;
1482 for (Dispatcher* pdispatcher : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001483 int fd = pdispatcher->GetDescriptor();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001484
jbauchde4db112017-05-31 13:09:18 -07001485 bool readable = FD_ISSET(fd, &fdsRead);
1486 if (readable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001487 FD_CLR(fd, &fdsRead);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001488 }
1489
jbauchde4db112017-05-31 13:09:18 -07001490 bool writable = FD_ISSET(fd, &fdsWrite);
1491 if (writable) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001492 FD_CLR(fd, &fdsWrite);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001493 }
1494
jbauchde4db112017-05-31 13:09:18 -07001495 // The error code can be signaled through reads or writes.
1496 ProcessEvents(pdispatcher, readable, writable, readable || writable);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001497 }
jbauchde4db112017-05-31 13:09:18 -07001498
1499 processing_dispatchers_ = false;
1500 // Process deferred dispatchers that have been added/removed while the
1501 // events were handled above.
1502 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001503 }
1504
1505 // Recalc the time remaining to wait. Doing it here means it doesn't get
1506 // calced twice the first time through the loop
1507 if (ptvWait) {
1508 ptvWait->tv_sec = 0;
1509 ptvWait->tv_usec = 0;
1510 struct timeval tvT;
deadbeef37f5ecf2017-02-27 14:06:41 -08001511 gettimeofday(&tvT, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001512 if ((tvStop.tv_sec > tvT.tv_sec)
1513 || ((tvStop.tv_sec == tvT.tv_sec)
1514 && (tvStop.tv_usec > tvT.tv_usec))) {
1515 ptvWait->tv_sec = tvStop.tv_sec - tvT.tv_sec;
1516 ptvWait->tv_usec = tvStop.tv_usec - tvT.tv_usec;
1517 if (ptvWait->tv_usec < 0) {
nisseede5da42017-01-12 05:15:36 -08001518 RTC_DCHECK(ptvWait->tv_sec > 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001519 ptvWait->tv_usec += 1000000;
1520 ptvWait->tv_sec -= 1;
1521 }
1522 }
1523 }
1524 }
1525
1526 return true;
1527}
1528
jbauchde4db112017-05-31 13:09:18 -07001529#if defined(WEBRTC_USE_EPOLL)
1530
1531// Initial number of events to process with one call to "epoll_wait".
1532static const size_t kInitialEpollEvents = 128;
1533
1534// Maximum number of events to process with one call to "epoll_wait".
1535static const size_t kMaxEpollEvents = 8192;
1536
1537void PhysicalSocketServer::AddEpoll(Dispatcher* pdispatcher) {
1538 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1539 int fd = pdispatcher->GetDescriptor();
1540 RTC_DCHECK(fd != INVALID_SOCKET);
1541 if (fd == INVALID_SOCKET) {
1542 return;
1543 }
1544
1545 struct epoll_event event = {0};
1546 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
1547 event.data.ptr = pdispatcher;
1548 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &event);
1549 RTC_DCHECK_EQ(err, 0);
1550 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001551 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_ADD";
jbauchde4db112017-05-31 13:09:18 -07001552 }
1553}
1554
1555void PhysicalSocketServer::RemoveEpoll(Dispatcher* pdispatcher) {
1556 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1557 int fd = pdispatcher->GetDescriptor();
1558 RTC_DCHECK(fd != INVALID_SOCKET);
1559 if (fd == INVALID_SOCKET) {
1560 return;
1561 }
1562
1563 struct epoll_event event = {0};
1564 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &event);
1565 RTC_DCHECK(err == 0 || errno == ENOENT);
1566 if (err == -1) {
1567 if (errno == ENOENT) {
1568 // Socket has already been closed.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001569 RTC_LOG_E(LS_VERBOSE, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001570 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001571 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
jbauchde4db112017-05-31 13:09:18 -07001572 }
1573 }
1574}
1575
1576void PhysicalSocketServer::UpdateEpoll(Dispatcher* pdispatcher) {
1577 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1578 int fd = pdispatcher->GetDescriptor();
1579 RTC_DCHECK(fd != INVALID_SOCKET);
1580 if (fd == INVALID_SOCKET) {
1581 return;
1582 }
1583
1584 struct epoll_event event = {0};
1585 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
1586 event.data.ptr = pdispatcher;
1587 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &event);
1588 RTC_DCHECK_EQ(err, 0);
1589 if (err == -1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001590 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_MOD";
jbauchde4db112017-05-31 13:09:18 -07001591 }
1592}
1593
1594bool PhysicalSocketServer::WaitEpoll(int cmsWait) {
1595 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1596 int64_t tvWait = -1;
1597 int64_t tvStop = -1;
1598 if (cmsWait != kForever) {
1599 tvWait = cmsWait;
1600 tvStop = TimeAfter(cmsWait);
1601 }
1602
1603 if (epoll_events_.empty()) {
1604 // The initial space to receive events is created only if epoll is used.
1605 epoll_events_.resize(kInitialEpollEvents);
1606 }
1607
1608 fWait_ = true;
1609
1610 while (fWait_) {
1611 // Wait then call handlers as appropriate
1612 // < 0 means error
1613 // 0 means timeout
1614 // > 0 means count of descriptors ready
1615 int n = epoll_wait(epoll_fd_, &epoll_events_[0],
1616 static_cast<int>(epoll_events_.size()),
1617 static_cast<int>(tvWait));
1618 if (n < 0) {
1619 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001620 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll";
jbauchde4db112017-05-31 13:09:18 -07001621 return false;
1622 }
1623 // Else ignore the error and keep going. If this EINTR was for one of the
1624 // signals managed by this PhysicalSocketServer, the
1625 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1626 // iteration.
1627 } else if (n == 0) {
1628 // If timeout, return success
1629 return true;
1630 } else {
1631 // We have signaled descriptors
1632 CritScope cr(&crit_);
1633 for (int i = 0; i < n; ++i) {
1634 const epoll_event& event = epoll_events_[i];
1635 Dispatcher* pdispatcher = static_cast<Dispatcher*>(event.data.ptr);
1636 if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1637 // The dispatcher for this socket no longer exists.
1638 continue;
1639 }
1640
1641 bool readable = (event.events & (EPOLLIN | EPOLLPRI));
1642 bool writable = (event.events & EPOLLOUT);
1643 bool check_error = (event.events & (EPOLLRDHUP | EPOLLERR | EPOLLHUP));
1644
1645 ProcessEvents(pdispatcher, readable, writable, check_error);
1646 }
1647 }
1648
1649 if (static_cast<size_t>(n) == epoll_events_.size() &&
1650 epoll_events_.size() < kMaxEpollEvents) {
1651 // We used the complete space to receive events, increase size for future
1652 // iterations.
1653 epoll_events_.resize(std::max(epoll_events_.size() * 2, kMaxEpollEvents));
1654 }
1655
1656 if (cmsWait != kForever) {
1657 tvWait = TimeDiff(tvStop, TimeMillis());
1658 if (tvWait < 0) {
1659 // Return success on timeout.
1660 return true;
1661 }
1662 }
1663 }
1664
1665 return true;
1666}
1667
1668bool PhysicalSocketServer::WaitPoll(int cmsWait, Dispatcher* dispatcher) {
1669 RTC_DCHECK(dispatcher);
1670 int64_t tvWait = -1;
1671 int64_t tvStop = -1;
1672 if (cmsWait != kForever) {
1673 tvWait = cmsWait;
1674 tvStop = TimeAfter(cmsWait);
1675 }
1676
1677 fWait_ = true;
1678
1679 struct pollfd fds = {0};
1680 int fd = dispatcher->GetDescriptor();
1681 fds.fd = fd;
1682
1683 while (fWait_) {
1684 uint32_t ff = dispatcher->GetRequestedEvents();
1685 fds.events = 0;
1686 if (ff & (DE_READ | DE_ACCEPT)) {
1687 fds.events |= POLLIN;
1688 }
1689 if (ff & (DE_WRITE | DE_CONNECT)) {
1690 fds.events |= POLLOUT;
1691 }
1692 fds.revents = 0;
1693
1694 // Wait then call handlers as appropriate
1695 // < 0 means error
1696 // 0 means timeout
1697 // > 0 means count of descriptors ready
1698 int n = poll(&fds, 1, static_cast<int>(tvWait));
1699 if (n < 0) {
1700 if (errno != EINTR) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001701 RTC_LOG_E(LS_ERROR, EN, errno) << "poll";
jbauchde4db112017-05-31 13:09:18 -07001702 return false;
1703 }
1704 // Else ignore the error and keep going. If this EINTR was for one of the
1705 // signals managed by this PhysicalSocketServer, the
1706 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1707 // iteration.
1708 } else if (n == 0) {
1709 // If timeout, return success
1710 return true;
1711 } else {
1712 // We have signaled descriptors (should only be the passed dispatcher).
1713 RTC_DCHECK_EQ(n, 1);
1714 RTC_DCHECK_EQ(fds.fd, fd);
1715
1716 bool readable = (fds.revents & (POLLIN | POLLPRI));
1717 bool writable = (fds.revents & POLLOUT);
1718 bool check_error = (fds.revents & (POLLRDHUP | POLLERR | POLLHUP));
1719
1720 ProcessEvents(dispatcher, readable, writable, check_error);
1721 }
1722
1723 if (cmsWait != kForever) {
1724 tvWait = TimeDiff(tvStop, TimeMillis());
1725 if (tvWait < 0) {
1726 // Return success on timeout.
1727 return true;
1728 }
1729 }
1730 }
1731
1732 return true;
1733}
1734
1735#endif // WEBRTC_USE_EPOLL
1736
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001737static void GlobalSignalHandler(int signum) {
1738 PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
1739}
1740
1741bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
1742 void (*handler)(int)) {
1743 // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
1744 // otherwise set one.
1745 if (handler == SIG_IGN || handler == SIG_DFL) {
1746 if (!InstallSignal(signum, handler)) {
1747 return false;
1748 }
1749 if (signal_dispatcher_) {
1750 signal_dispatcher_->ClearHandler(signum);
1751 if (!signal_dispatcher_->HasHandlers()) {
1752 signal_dispatcher_.reset();
1753 }
1754 }
1755 } else {
1756 if (!signal_dispatcher_) {
1757 signal_dispatcher_.reset(new PosixSignalDispatcher(this));
1758 }
1759 signal_dispatcher_->SetHandler(signum, handler);
1760 if (!InstallSignal(signum, &GlobalSignalHandler)) {
1761 return false;
1762 }
1763 }
1764 return true;
1765}
1766
1767Dispatcher* PhysicalSocketServer::signal_dispatcher() {
1768 return signal_dispatcher_.get();
1769}
1770
1771bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
1772 struct sigaction act;
1773 // It doesn't really matter what we set this mask to.
1774 if (sigemptyset(&act.sa_mask) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001775 RTC_LOG_ERR(LS_ERROR) << "Couldn't set mask";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001776 return false;
1777 }
1778 act.sa_handler = handler;
1779#if !defined(__native_client__)
1780 // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
1781 // and it's a nuisance. Though some syscalls still return EINTR and there's no
1782 // real standard for which ones. :(
1783 act.sa_flags = SA_RESTART;
1784#else
1785 act.sa_flags = 0;
1786#endif
deadbeef37f5ecf2017-02-27 14:06:41 -08001787 if (sigaction(signum, &act, nullptr) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001788 RTC_LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001789 return false;
1790 }
1791 return true;
1792}
1793#endif // WEBRTC_POSIX
1794
1795#if defined(WEBRTC_WIN)
1796bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
Honghai Zhang82d78622016-05-06 11:29:15 -07001797 int64_t cmsTotal = cmsWait;
1798 int64_t cmsElapsed = 0;
1799 int64_t msStart = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001800
1801 fWait_ = true;
1802 while (fWait_) {
1803 std::vector<WSAEVENT> events;
1804 std::vector<Dispatcher *> event_owners;
1805
1806 events.push_back(socket_ev_);
1807
1808 {
1809 CritScope cr(&crit_);
jbauchde4db112017-05-31 13:09:18 -07001810 // TODO(jbauch): Support re-entrant waiting.
1811 RTC_DCHECK(!processing_dispatchers_);
1812
1813 // Calling "CheckSignalClose" might remove a closed dispatcher from the
1814 // set. This must be deferred to prevent invalidating the iterator.
1815 processing_dispatchers_ = true;
1816 for (Dispatcher* disp : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001817 if (!process_io && (disp != signal_wakeup_))
1818 continue;
1819 SOCKET s = disp->GetSocket();
1820 if (disp->CheckSignalClose()) {
1821 // We just signalled close, don't poll this socket
1822 } else if (s != INVALID_SOCKET) {
1823 WSAEventSelect(s,
1824 events[0],
1825 FlagsToEvents(disp->GetRequestedEvents()));
1826 } else {
1827 events.push_back(disp->GetWSAEvent());
1828 event_owners.push_back(disp);
1829 }
1830 }
jbauchde4db112017-05-31 13:09:18 -07001831
1832 processing_dispatchers_ = false;
1833 // Process deferred dispatchers that have been added/removed while the
1834 // events were handled above.
1835 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001836 }
1837
1838 // Which is shorter, the delay wait or the asked wait?
1839
Honghai Zhang82d78622016-05-06 11:29:15 -07001840 int64_t cmsNext;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001841 if (cmsWait == kForever) {
1842 cmsNext = cmsWait;
1843 } else {
Honghai Zhang82d78622016-05-06 11:29:15 -07001844 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001845 }
1846
1847 // Wait for one of the events to signal
1848 DWORD dw = WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()),
1849 &events[0],
1850 false,
Honghai Zhang82d78622016-05-06 11:29:15 -07001851 static_cast<DWORD>(cmsNext),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001852 false);
1853
1854 if (dw == WSA_WAIT_FAILED) {
1855 // Failed?
jbauch095ae152015-12-18 01:39:55 -08001856 // TODO(pthatcher): need a better strategy than this!
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001857 WSAGetLastError();
nissec80e7412017-01-11 05:56:46 -08001858 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001859 return false;
1860 } else if (dw == WSA_WAIT_TIMEOUT) {
1861 // Timeout?
1862 return true;
1863 } else {
1864 // Figure out which one it is and call it
1865 CritScope cr(&crit_);
1866 int index = dw - WSA_WAIT_EVENT_0;
1867 if (index > 0) {
1868 --index; // The first event is the socket event
jbauchde4db112017-05-31 13:09:18 -07001869 Dispatcher* disp = event_owners[index];
1870 // The dispatcher could have been removed while waiting for events.
1871 if (dispatchers_.find(disp) != dispatchers_.end()) {
1872 disp->OnPreEvent(0);
1873 disp->OnEvent(0, 0);
1874 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001875 } else if (process_io) {
jbauchde4db112017-05-31 13:09:18 -07001876 processing_dispatchers_ = true;
1877 for (Dispatcher* disp : dispatchers_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001878 SOCKET s = disp->GetSocket();
1879 if (s == INVALID_SOCKET)
1880 continue;
1881
1882 WSANETWORKEVENTS wsaEvents;
1883 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1884 if (err == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001885 {
1886 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1887 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001888 RTC_LOG(WARNING)
1889 << "PhysicalSocketServer got FD_READ_BIT error "
1890 << wsaEvents.iErrorCode[FD_READ_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001891 }
1892 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1893 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001894 RTC_LOG(WARNING)
1895 << "PhysicalSocketServer got FD_WRITE_BIT error "
1896 << wsaEvents.iErrorCode[FD_WRITE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001897 }
1898 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1899 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001900 RTC_LOG(WARNING)
1901 << "PhysicalSocketServer got FD_CONNECT_BIT error "
1902 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001903 }
1904 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1905 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001906 RTC_LOG(WARNING)
1907 << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1908 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001909 }
1910 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1911 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001912 RTC_LOG(WARNING)
1913 << "PhysicalSocketServer got FD_CLOSE_BIT error "
1914 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001915 }
1916 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001917 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001918 int errcode = 0;
1919 if (wsaEvents.lNetworkEvents & FD_READ)
1920 ff |= DE_READ;
1921 if (wsaEvents.lNetworkEvents & FD_WRITE)
1922 ff |= DE_WRITE;
1923 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1924 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1925 ff |= DE_CONNECT;
1926 } else {
1927 ff |= DE_CLOSE;
1928 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1929 }
1930 }
1931 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1932 ff |= DE_ACCEPT;
1933 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1934 ff |= DE_CLOSE;
1935 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1936 }
1937 if (ff != 0) {
1938 disp->OnPreEvent(ff);
1939 disp->OnEvent(ff, errcode);
1940 }
1941 }
1942 }
jbauchde4db112017-05-31 13:09:18 -07001943
1944 processing_dispatchers_ = false;
1945 // Process deferred dispatchers that have been added/removed while the
1946 // events were handled above.
1947 AddRemovePendingDispatchers();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001948 }
1949
1950 // Reset the network event until new activity occurs
1951 WSAResetEvent(socket_ev_);
1952 }
1953
1954 // Break?
1955 if (!fWait_)
1956 break;
1957 cmsElapsed = TimeSince(msStart);
1958 if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
1959 break;
1960 }
1961 }
1962
1963 // Done
1964 return true;
1965}
honghaizcec0a082016-01-15 14:49:09 -08001966#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001967
1968} // namespace rtc