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