blob: a412703015e77f903b82c6126edd21a4c00a023d [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 */
honghaizcec0a082016-01-15 14:49:09 -080010#include "webrtc/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>
Stefan Holmer9131efd2016-05-23 18:19:26 +020024#include <sys/ioctl.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000025#include <sys/time.h>
26#include <sys/select.h>
27#include <unistd.h>
28#include <signal.h>
29#endif
30
31#if defined(WEBRTC_WIN)
32#define WIN32_LEAN_AND_MEAN
33#include <windows.h>
34#include <winsock2.h>
35#include <ws2tcpip.h>
36#undef SetPort
37#endif
38
39#include <algorithm>
40#include <map>
41
tfarina5237aaf2015-11-10 23:44:30 -080042#include "webrtc/base/arraysize.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000043#include "webrtc/base/basictypes.h"
44#include "webrtc/base/byteorder.h"
nissec80e7412017-01-11 05:56:46 -080045#include "webrtc/base/checks.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000046#include "webrtc/base/logging.h"
honghaizcec0a082016-01-15 14:49:09 -080047#include "webrtc/base/networkmonitor.h"
danilchapbebf54c2016-04-28 01:32:48 -070048#include "webrtc/base/nullsocketserver.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000049#include "webrtc/base/timeutils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000050#include "webrtc/base/win32socketinit.h"
51
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000052#if defined(WEBRTC_POSIX)
53#include <netinet/tcp.h> // for TCP_NODELAY
54#define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h
55typedef void* SockOptArg;
Stefan Holmer9131efd2016-05-23 18:19:26 +020056
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000057#endif // WEBRTC_POSIX
58
Stefan Holmer3ebb3ef2016-05-23 20:26:11 +020059#if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) && !defined(__native_client__)
60
Stefan Holmer9131efd2016-05-23 18:19:26 +020061int64_t GetSocketRecvTimestamp(int socket) {
62 struct timeval tv_ioctl;
63 int ret = ioctl(socket, SIOCGSTAMP, &tv_ioctl);
64 if (ret != 0)
65 return -1;
66 int64_t timestamp =
67 rtc::kNumMicrosecsPerSec * static_cast<int64_t>(tv_ioctl.tv_sec) +
68 static_cast<int64_t>(tv_ioctl.tv_usec);
69 return timestamp;
70}
71
72#else
73
74int64_t GetSocketRecvTimestamp(int socket) {
75 return -1;
76}
77#endif
78
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000079#if defined(WEBRTC_WIN)
80typedef char* SockOptArg;
81#endif
82
83namespace rtc {
84
danilchapbebf54c2016-04-28 01:32:48 -070085std::unique_ptr<SocketServer> SocketServer::CreateDefault() {
86#if defined(__native_client__)
87 return std::unique_ptr<SocketServer>(new rtc::NullSocketServer);
88#else
89 return std::unique_ptr<SocketServer>(new rtc::PhysicalSocketServer);
90#endif
91}
92
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000093#if defined(WEBRTC_WIN)
94// Standard MTUs, from RFC 1191
Peter Boström0c4e06b2015-10-07 12:23:21 +020095const uint16_t PACKET_MAXIMUMS[] = {
96 65535, // Theoretical maximum, Hyperchannel
97 32000, // Nothing
98 17914, // 16Mb IBM Token Ring
99 8166, // IEEE 802.4
100 // 4464, // IEEE 802.5 (4Mb max)
101 4352, // FDDI
102 // 2048, // Wideband Network
103 2002, // IEEE 802.5 (4Mb recommended)
104 // 1536, // Expermental Ethernet Networks
105 // 1500, // Ethernet, Point-to-Point (default)
106 1492, // IEEE 802.3
107 1006, // SLIP, ARPANET
108 // 576, // X.25 Networks
109 // 544, // DEC IP Portal
110 // 512, // NETBIOS
111 508, // IEEE 802/Source-Rt Bridge, ARCNET
112 296, // Point-to-Point (low delay)
113 68, // Official minimum
114 0, // End of list marker
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000115};
116
117static const int IP_HEADER_SIZE = 20u;
118static const int IPV6_HEADER_SIZE = 40u;
119static const int ICMP_HEADER_SIZE = 8u;
120static const int ICMP_PING_TIMEOUT_MILLIS = 10000u;
121#endif
122
jbauch095ae152015-12-18 01:39:55 -0800123PhysicalSocket::PhysicalSocket(PhysicalSocketServer* ss, SOCKET s)
jbauch577f5dc2017-05-17 16:32:26 -0700124 : ss_(ss), s_(s), error_(0),
jbauch095ae152015-12-18 01:39:55 -0800125 state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED),
126 resolver_(nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000127#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800128 // EnsureWinsockInit() ensures that winsock is initialized. The default
129 // version of this function doesn't do anything because winsock is
130 // initialized by constructor of a static object. If neccessary libjingle
131 // users can link it with a different version of this function by replacing
132 // win32socketinit.cc. See win32socketinit.cc for more details.
133 EnsureWinsockInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000134#endif
jbauch095ae152015-12-18 01:39:55 -0800135 if (s_ != INVALID_SOCKET) {
jbauch577f5dc2017-05-17 16:32:26 -0700136 SetEnabledEvents(DE_READ | DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000137
jbauch095ae152015-12-18 01:39:55 -0800138 int type = SOCK_STREAM;
139 socklen_t len = sizeof(type);
nissec16fa5e2017-02-07 07:18:43 -0800140 const int res =
141 getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len);
142 RTC_DCHECK_EQ(0, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000143 udp_ = (SOCK_DGRAM == type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000144 }
jbauch095ae152015-12-18 01:39:55 -0800145}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000146
jbauch095ae152015-12-18 01:39:55 -0800147PhysicalSocket::~PhysicalSocket() {
148 Close();
149}
150
151bool PhysicalSocket::Create(int family, int type) {
152 Close();
153 s_ = ::socket(family, type, 0);
154 udp_ = (SOCK_DGRAM == type);
155 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700156 if (udp_) {
157 SetEnabledEvents(DE_READ | DE_WRITE);
158 }
jbauch095ae152015-12-18 01:39:55 -0800159 return s_ != INVALID_SOCKET;
160}
161
162SocketAddress PhysicalSocket::GetLocalAddress() const {
163 sockaddr_storage addr_storage = {0};
164 socklen_t addrlen = sizeof(addr_storage);
165 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
166 int result = ::getsockname(s_, addr, &addrlen);
167 SocketAddress address;
168 if (result >= 0) {
169 SocketAddressFromSockAddrStorage(addr_storage, &address);
170 } else {
171 LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
172 << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000173 }
jbauch095ae152015-12-18 01:39:55 -0800174 return address;
175}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000176
jbauch095ae152015-12-18 01:39:55 -0800177SocketAddress PhysicalSocket::GetRemoteAddress() const {
178 sockaddr_storage addr_storage = {0};
179 socklen_t addrlen = sizeof(addr_storage);
180 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
181 int result = ::getpeername(s_, addr, &addrlen);
182 SocketAddress address;
183 if (result >= 0) {
184 SocketAddressFromSockAddrStorage(addr_storage, &address);
185 } else {
186 LOG(LS_WARNING) << "GetRemoteAddress: unable to get remote addr, socket="
187 << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000188 }
jbauch095ae152015-12-18 01:39:55 -0800189 return address;
190}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000191
jbauch095ae152015-12-18 01:39:55 -0800192int PhysicalSocket::Bind(const SocketAddress& bind_addr) {
deadbeefc874d122017-02-13 15:41:59 -0800193 SocketAddress copied_bind_addr = bind_addr;
194 // If a network binder is available, use it to bind a socket to an interface
195 // instead of bind(), since this is more reliable on an OS with a weak host
196 // model.
deadbeef9ffa13f2017-02-21 16:18:00 -0800197 if (ss_->network_binder() && !bind_addr.IsAnyIP()) {
deadbeefc874d122017-02-13 15:41:59 -0800198 NetworkBindingResult result =
199 ss_->network_binder()->BindSocketToNetwork(s_, bind_addr.ipaddr());
200 if (result == NetworkBindingResult::SUCCESS) {
201 // Since the network binder handled binding the socket to the desired
202 // network interface, we don't need to (and shouldn't) include an IP in
203 // the bind() call; bind() just needs to assign a port.
204 copied_bind_addr.SetIP(GetAnyIP(copied_bind_addr.ipaddr().family()));
205 } else if (result == NetworkBindingResult::NOT_IMPLEMENTED) {
206 LOG(LS_INFO) << "Can't bind socket to network because "
207 "network binding is not implemented for this OS.";
208 } else {
209 if (bind_addr.IsLoopbackIP()) {
210 // If we couldn't bind to a loopback IP (which should only happen in
211 // test scenarios), continue on. This may be expected behavior.
212 LOG(LS_VERBOSE) << "Binding socket to loopback address "
213 << bind_addr.ipaddr().ToString()
214 << " failed; result: " << static_cast<int>(result);
215 } else {
216 LOG(LS_WARNING) << "Binding socket to network address "
217 << bind_addr.ipaddr().ToString()
218 << " failed; result: " << static_cast<int>(result);
219 // If a network binding was attempted and failed, we should stop here
220 // and not try to use the socket. Otherwise, we may end up sending
221 // packets with an invalid source address.
222 // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=7026
223 return -1;
224 }
225 }
226 }
jbauch095ae152015-12-18 01:39:55 -0800227 sockaddr_storage addr_storage;
deadbeefc874d122017-02-13 15:41:59 -0800228 size_t len = copied_bind_addr.ToSockAddrStorage(&addr_storage);
jbauch095ae152015-12-18 01:39:55 -0800229 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
230 int err = ::bind(s_, addr, static_cast<int>(len));
231 UpdateLastError();
tfarinaa41ab932015-10-30 16:08:48 -0700232#if !defined(NDEBUG)
jbauch095ae152015-12-18 01:39:55 -0800233 if (0 == err) {
234 dbg_addr_ = "Bound @ ";
235 dbg_addr_.append(GetLocalAddress().ToString());
236 }
tfarinaa41ab932015-10-30 16:08:48 -0700237#endif
jbauch095ae152015-12-18 01:39:55 -0800238 return err;
239}
240
241int PhysicalSocket::Connect(const SocketAddress& addr) {
242 // TODO(pthatcher): Implicit creation is required to reconnect...
243 // ...but should we make it more explicit?
244 if (state_ != CS_CLOSED) {
245 SetError(EALREADY);
246 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000247 }
jbauch095ae152015-12-18 01:39:55 -0800248 if (addr.IsUnresolvedIP()) {
249 LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
250 resolver_ = new AsyncResolver();
251 resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult);
252 resolver_->Start(addr);
253 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254 return 0;
255 }
256
jbauch095ae152015-12-18 01:39:55 -0800257 return DoConnect(addr);
258}
259
260int PhysicalSocket::DoConnect(const SocketAddress& connect_addr) {
261 if ((s_ == INVALID_SOCKET) &&
262 !Create(connect_addr.family(), SOCK_STREAM)) {
263 return SOCKET_ERROR;
264 }
265 sockaddr_storage addr_storage;
266 size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
267 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
268 int err = ::connect(s_, addr, static_cast<int>(len));
269 UpdateLastError();
jbauch577f5dc2017-05-17 16:32:26 -0700270 uint8_t events = DE_READ | DE_WRITE;
jbauch095ae152015-12-18 01:39:55 -0800271 if (err == 0) {
272 state_ = CS_CONNECTED;
273 } else if (IsBlockingError(GetError())) {
274 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700275 events |= DE_CONNECT;
jbauch095ae152015-12-18 01:39:55 -0800276 } else {
277 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000278 }
279
jbauch577f5dc2017-05-17 16:32:26 -0700280 EnableEvents(events);
jbauch095ae152015-12-18 01:39:55 -0800281 return 0;
282}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000283
jbauch095ae152015-12-18 01:39:55 -0800284int PhysicalSocket::GetError() const {
285 CritScope cs(&crit_);
286 return error_;
287}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000288
jbauch095ae152015-12-18 01:39:55 -0800289void PhysicalSocket::SetError(int error) {
290 CritScope cs(&crit_);
291 error_ = error;
292}
293
294AsyncSocket::ConnState PhysicalSocket::GetState() const {
295 return state_;
296}
297
298int PhysicalSocket::GetOption(Option opt, int* value) {
299 int slevel;
300 int sopt;
301 if (TranslateOption(opt, &slevel, &sopt) == -1)
302 return -1;
303 socklen_t optlen = sizeof(*value);
304 int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
305 if (ret != -1 && opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000306#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800307 *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000308#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000309 }
jbauch095ae152015-12-18 01:39:55 -0800310 return ret;
311}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000312
jbauch095ae152015-12-18 01:39:55 -0800313int PhysicalSocket::SetOption(Option opt, int value) {
314 int slevel;
315 int sopt;
316 if (TranslateOption(opt, &slevel, &sopt) == -1)
317 return -1;
318 if (opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000319#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800320 value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000321#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000322 }
jbauch095ae152015-12-18 01:39:55 -0800323 return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
324}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000325
jbauch095ae152015-12-18 01:39:55 -0800326int PhysicalSocket::Send(const void* pv, size_t cb) {
jbauchf2a2bf42016-02-03 16:45:32 -0800327 int sent = DoSend(s_, reinterpret_cast<const char *>(pv),
328 static_cast<int>(cb),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000329#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800330 // Suppress SIGPIPE. Without this, attempting to send on a socket whose
331 // other end is closed will result in a SIGPIPE signal being raised to
332 // our process, which by default will terminate the process, which we
333 // don't want. By specifying this flag, we'll just get the error EPIPE
334 // instead and can handle the error gracefully.
335 MSG_NOSIGNAL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000336#else
jbauch095ae152015-12-18 01:39:55 -0800337 0
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000338#endif
jbauch095ae152015-12-18 01:39:55 -0800339 );
340 UpdateLastError();
341 MaybeRemapSendError();
342 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800343 RTC_DCHECK(sent <= static_cast<int>(cb));
jbauchf2a2bf42016-02-03 16:45:32 -0800344 if ((sent > 0 && sent < static_cast<int>(cb)) ||
345 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700346 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000347 }
jbauch095ae152015-12-18 01:39:55 -0800348 return sent;
349}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000350
jbauch095ae152015-12-18 01:39:55 -0800351int PhysicalSocket::SendTo(const void* buffer,
352 size_t length,
353 const SocketAddress& addr) {
354 sockaddr_storage saddr;
355 size_t len = addr.ToSockAddrStorage(&saddr);
jbauchf2a2bf42016-02-03 16:45:32 -0800356 int sent = DoSendTo(
jbauch095ae152015-12-18 01:39:55 -0800357 s_, static_cast<const char *>(buffer), static_cast<int>(length),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000358#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800359 // Suppress SIGPIPE. See above for explanation.
360 MSG_NOSIGNAL,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000361#else
jbauch095ae152015-12-18 01:39:55 -0800362 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000363#endif
jbauch095ae152015-12-18 01:39:55 -0800364 reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
365 UpdateLastError();
366 MaybeRemapSendError();
367 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800368 RTC_DCHECK(sent <= static_cast<int>(length));
jbauchf2a2bf42016-02-03 16:45:32 -0800369 if ((sent > 0 && sent < static_cast<int>(length)) ||
370 (sent < 0 && IsBlockingError(GetError()))) {
jbauch577f5dc2017-05-17 16:32:26 -0700371 EnableEvents(DE_WRITE);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000372 }
jbauch095ae152015-12-18 01:39:55 -0800373 return sent;
374}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000375
Stefan Holmer9131efd2016-05-23 18:19:26 +0200376int PhysicalSocket::Recv(void* buffer, size_t length, int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800377 int received = ::recv(s_, static_cast<char*>(buffer),
378 static_cast<int>(length), 0);
379 if ((received == 0) && (length != 0)) {
380 // Note: on graceful shutdown, recv can return 0. In this case, we
381 // pretend it is blocking, and then signal close, so that simplifying
382 // assumptions can be made about Recv.
383 LOG(LS_WARNING) << "EOF from socket; deferring close event";
384 // Must turn this back on so that the select() loop will notice the close
385 // event.
jbauch577f5dc2017-05-17 16:32:26 -0700386 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800387 SetError(EWOULDBLOCK);
388 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000389 }
Stefan Holmer9131efd2016-05-23 18:19:26 +0200390 if (timestamp) {
391 *timestamp = GetSocketRecvTimestamp(s_);
392 }
jbauch095ae152015-12-18 01:39:55 -0800393 UpdateLastError();
394 int error = GetError();
395 bool success = (received >= 0) || IsBlockingError(error);
396 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700397 EnableEvents(DE_READ);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000398 }
jbauch095ae152015-12-18 01:39:55 -0800399 if (!success) {
400 LOG_F(LS_VERBOSE) << "Error = " << error;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000401 }
jbauch095ae152015-12-18 01:39:55 -0800402 return received;
403}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000404
jbauch095ae152015-12-18 01:39:55 -0800405int PhysicalSocket::RecvFrom(void* buffer,
406 size_t length,
Stefan Holmer9131efd2016-05-23 18:19:26 +0200407 SocketAddress* out_addr,
408 int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800409 sockaddr_storage addr_storage;
410 socklen_t addr_len = sizeof(addr_storage);
411 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
412 int received = ::recvfrom(s_, static_cast<char*>(buffer),
413 static_cast<int>(length), 0, addr, &addr_len);
Stefan Holmer9131efd2016-05-23 18:19:26 +0200414 if (timestamp) {
415 *timestamp = GetSocketRecvTimestamp(s_);
416 }
jbauch095ae152015-12-18 01:39:55 -0800417 UpdateLastError();
418 if ((received >= 0) && (out_addr != nullptr))
419 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
420 int error = GetError();
421 bool success = (received >= 0) || IsBlockingError(error);
422 if (udp_ || success) {
jbauch577f5dc2017-05-17 16:32:26 -0700423 EnableEvents(DE_READ);
jbauch095ae152015-12-18 01:39:55 -0800424 }
425 if (!success) {
426 LOG_F(LS_VERBOSE) << "Error = " << error;
427 }
428 return received;
429}
430
431int PhysicalSocket::Listen(int backlog) {
432 int err = ::listen(s_, backlog);
433 UpdateLastError();
434 if (err == 0) {
435 state_ = CS_CONNECTING;
jbauch577f5dc2017-05-17 16:32:26 -0700436 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800437#if !defined(NDEBUG)
438 dbg_addr_ = "Listening @ ";
439 dbg_addr_.append(GetLocalAddress().ToString());
440#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000441 }
jbauch095ae152015-12-18 01:39:55 -0800442 return err;
443}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000444
jbauch095ae152015-12-18 01:39:55 -0800445AsyncSocket* PhysicalSocket::Accept(SocketAddress* out_addr) {
446 // Always re-subscribe DE_ACCEPT to make sure new incoming connections will
447 // trigger an event even if DoAccept returns an error here.
jbauch577f5dc2017-05-17 16:32:26 -0700448 EnableEvents(DE_ACCEPT);
jbauch095ae152015-12-18 01:39:55 -0800449 sockaddr_storage addr_storage;
450 socklen_t addr_len = sizeof(addr_storage);
451 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
452 SOCKET s = DoAccept(s_, addr, &addr_len);
453 UpdateLastError();
454 if (s == INVALID_SOCKET)
455 return nullptr;
456 if (out_addr != nullptr)
457 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
458 return ss_->WrapSocket(s);
459}
460
461int PhysicalSocket::Close() {
462 if (s_ == INVALID_SOCKET)
463 return 0;
464 int err = ::closesocket(s_);
465 UpdateLastError();
466 s_ = INVALID_SOCKET;
467 state_ = CS_CLOSED;
jbauch577f5dc2017-05-17 16:32:26 -0700468 SetEnabledEvents(0);
jbauch095ae152015-12-18 01:39:55 -0800469 if (resolver_) {
470 resolver_->Destroy(false);
471 resolver_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000472 }
jbauch095ae152015-12-18 01:39:55 -0800473 return err;
474}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000475
jbauch095ae152015-12-18 01:39:55 -0800476SOCKET PhysicalSocket::DoAccept(SOCKET socket,
477 sockaddr* addr,
478 socklen_t* addrlen) {
479 return ::accept(socket, addr, addrlen);
480}
481
jbauchf2a2bf42016-02-03 16:45:32 -0800482int PhysicalSocket::DoSend(SOCKET socket, const char* buf, int len, int flags) {
483 return ::send(socket, buf, len, flags);
484}
485
486int PhysicalSocket::DoSendTo(SOCKET socket,
487 const char* buf,
488 int len,
489 int flags,
490 const struct sockaddr* dest_addr,
491 socklen_t addrlen) {
492 return ::sendto(socket, buf, len, flags, dest_addr, addrlen);
493}
494
jbauch095ae152015-12-18 01:39:55 -0800495void PhysicalSocket::OnResolveResult(AsyncResolverInterface* resolver) {
496 if (resolver != resolver_) {
497 return;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000498 }
499
jbauch095ae152015-12-18 01:39:55 -0800500 int error = resolver_->GetError();
501 if (error == 0) {
502 error = DoConnect(resolver_->address());
503 } else {
504 Close();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000505 }
506
jbauch095ae152015-12-18 01:39:55 -0800507 if (error) {
508 SetError(error);
509 SignalCloseEvent(this, error);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000510 }
jbauch095ae152015-12-18 01:39:55 -0800511}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000512
jbauch095ae152015-12-18 01:39:55 -0800513void PhysicalSocket::UpdateLastError() {
514 SetError(LAST_SYSTEM_ERROR);
515}
516
517void PhysicalSocket::MaybeRemapSendError() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000518#if defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800519 // https://developer.apple.com/library/mac/documentation/Darwin/
520 // Reference/ManPages/man2/sendto.2.html
521 // ENOBUFS - The output queue for a network interface is full.
522 // This generally indicates that the interface has stopped sending,
523 // but may be caused by transient congestion.
524 if (GetError() == ENOBUFS) {
525 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000526 }
jbauch095ae152015-12-18 01:39:55 -0800527#endif
528}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000529
jbauch577f5dc2017-05-17 16:32:26 -0700530void PhysicalSocket::SetEnabledEvents(uint8_t events) {
531 enabled_events_ = events;
532}
533
534void PhysicalSocket::EnableEvents(uint8_t events) {
535 enabled_events_ |= events;
536}
537
538void PhysicalSocket::DisableEvents(uint8_t events) {
539 enabled_events_ &= ~events;
540}
541
jbauch095ae152015-12-18 01:39:55 -0800542int PhysicalSocket::TranslateOption(Option opt, int* slevel, int* sopt) {
543 switch (opt) {
544 case OPT_DONTFRAGMENT:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000545#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800546 *slevel = IPPROTO_IP;
547 *sopt = IP_DONTFRAGMENT;
548 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000549#elif defined(WEBRTC_MAC) || defined(BSD) || defined(__native_client__)
jbauch095ae152015-12-18 01:39:55 -0800550 LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
551 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000552#elif defined(WEBRTC_POSIX)
jbauch095ae152015-12-18 01:39:55 -0800553 *slevel = IPPROTO_IP;
554 *sopt = IP_MTU_DISCOVER;
555 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000556#endif
jbauch095ae152015-12-18 01:39:55 -0800557 case OPT_RCVBUF:
558 *slevel = SOL_SOCKET;
559 *sopt = SO_RCVBUF;
560 break;
561 case OPT_SNDBUF:
562 *slevel = SOL_SOCKET;
563 *sopt = SO_SNDBUF;
564 break;
565 case OPT_NODELAY:
566 *slevel = IPPROTO_TCP;
567 *sopt = TCP_NODELAY;
568 break;
569 case OPT_DSCP:
570 LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
571 return -1;
572 case OPT_RTP_SENDTIME_EXTN_ID:
573 return -1; // No logging is necessary as this not a OS socket option.
574 default:
nissec80e7412017-01-11 05:56:46 -0800575 RTC_NOTREACHED();
jbauch095ae152015-12-18 01:39:55 -0800576 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000577 }
jbauch095ae152015-12-18 01:39:55 -0800578 return 0;
579}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000580
jbauch4331fcd2016-01-06 22:20:28 -0800581SocketDispatcher::SocketDispatcher(PhysicalSocketServer *ss)
582#if defined(WEBRTC_WIN)
583 : PhysicalSocket(ss), id_(0), signal_close_(false)
584#else
585 : PhysicalSocket(ss)
586#endif
587{
588}
589
590SocketDispatcher::SocketDispatcher(SOCKET s, PhysicalSocketServer *ss)
591#if defined(WEBRTC_WIN)
592 : PhysicalSocket(ss, s), id_(0), signal_close_(false)
593#else
594 : PhysicalSocket(ss, s)
595#endif
596{
597}
598
599SocketDispatcher::~SocketDispatcher() {
600 Close();
601}
602
603bool SocketDispatcher::Initialize() {
nisseede5da42017-01-12 05:15:36 -0800604 RTC_DCHECK(s_ != INVALID_SOCKET);
jbauch4331fcd2016-01-06 22:20:28 -0800605 // Must be a non-blocking
606#if defined(WEBRTC_WIN)
607 u_long argp = 1;
608 ioctlsocket(s_, FIONBIO, &argp);
609#elif defined(WEBRTC_POSIX)
610 fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
611#endif
612 ss_->Add(this);
613 return true;
614}
615
616bool SocketDispatcher::Create(int type) {
617 return Create(AF_INET, type);
618}
619
620bool SocketDispatcher::Create(int family, int type) {
621 // Change the socket to be non-blocking.
622 if (!PhysicalSocket::Create(family, type))
623 return false;
624
625 if (!Initialize())
626 return false;
627
628#if defined(WEBRTC_WIN)
629 do { id_ = ++next_id_; } while (id_ == 0);
630#endif
631 return true;
632}
633
634#if defined(WEBRTC_WIN)
635
636WSAEVENT SocketDispatcher::GetWSAEvent() {
637 return WSA_INVALID_EVENT;
638}
639
640SOCKET SocketDispatcher::GetSocket() {
641 return s_;
642}
643
644bool SocketDispatcher::CheckSignalClose() {
645 if (!signal_close_)
646 return false;
647
648 char ch;
649 if (recv(s_, &ch, 1, MSG_PEEK) > 0)
650 return false;
651
652 state_ = CS_CLOSED;
653 signal_close_ = false;
654 SignalCloseEvent(this, signal_err_);
655 return true;
656}
657
658int SocketDispatcher::next_id_ = 0;
659
660#elif defined(WEBRTC_POSIX)
661
662int SocketDispatcher::GetDescriptor() {
663 return s_;
664}
665
666bool SocketDispatcher::IsDescriptorClosed() {
deadbeeffaedf7f2017-02-09 15:09:22 -0800667 if (udp_) {
668 // The MSG_PEEK trick doesn't work for UDP, since (at least in some
669 // circumstances) it requires reading an entire UDP packet, which would be
670 // bad for performance here. So, just check whether |s_| has been closed,
671 // which should be sufficient.
672 return s_ == INVALID_SOCKET;
673 }
jbauch4331fcd2016-01-06 22:20:28 -0800674 // We don't have a reliable way of distinguishing end-of-stream
675 // from readability. So test on each readable call. Is this
676 // inefficient? Probably.
677 char ch;
678 ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
679 if (res > 0) {
680 // Data available, so not closed.
681 return false;
682 } else if (res == 0) {
683 // EOF, so closed.
684 return true;
685 } else { // error
686 switch (errno) {
687 // Returned if we've already closed s_.
688 case EBADF:
689 // Returned during ungraceful peer shutdown.
690 case ECONNRESET:
691 return true;
deadbeeffaedf7f2017-02-09 15:09:22 -0800692 // The normal blocking error; don't log anything.
693 case EWOULDBLOCK:
694 // Interrupted system call.
695 case EINTR:
696 return false;
jbauch4331fcd2016-01-06 22:20:28 -0800697 default:
698 // Assume that all other errors are just blocking errors, meaning the
699 // connection is still good but we just can't read from it right now.
700 // This should only happen when connecting (and at most once), because
701 // in all other cases this function is only called if the file
702 // descriptor is already known to be in the readable state. However,
703 // it's not necessary a problem if we spuriously interpret a
704 // "connection lost"-type error as a blocking error, because typically
705 // the next recv() will get EOF, so we'll still eventually notice that
706 // the socket is closed.
707 LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
708 return false;
709 }
710 }
711}
712
713#endif // WEBRTC_POSIX
714
715uint32_t SocketDispatcher::GetRequestedEvents() {
jbauch577f5dc2017-05-17 16:32:26 -0700716 return enabled_events();
jbauch4331fcd2016-01-06 22:20:28 -0800717}
718
719void SocketDispatcher::OnPreEvent(uint32_t ff) {
720 if ((ff & DE_CONNECT) != 0)
721 state_ = CS_CONNECTED;
722
723#if defined(WEBRTC_WIN)
724 // We set CS_CLOSED from CheckSignalClose.
725#elif defined(WEBRTC_POSIX)
726 if ((ff & DE_CLOSE) != 0)
727 state_ = CS_CLOSED;
728#endif
729}
730
731#if defined(WEBRTC_WIN)
732
733void SocketDispatcher::OnEvent(uint32_t ff, int err) {
734 int cache_id = id_;
735 // Make sure we deliver connect/accept first. Otherwise, consumers may see
736 // something like a READ followed by a CONNECT, which would be odd.
737 if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
738 if (ff != DE_CONNECT)
739 LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
jbauch577f5dc2017-05-17 16:32:26 -0700740 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800741#if !defined(NDEBUG)
742 dbg_addr_ = "Connected @ ";
743 dbg_addr_.append(GetRemoteAddress().ToString());
744#endif
745 SignalConnectEvent(this);
746 }
747 if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700748 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800749 SignalReadEvent(this);
750 }
751 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700752 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800753 SignalReadEvent(this);
754 }
755 if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700756 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800757 SignalWriteEvent(this);
758 }
759 if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
760 signal_close_ = true;
761 signal_err_ = err;
762 }
763}
764
765#elif defined(WEBRTC_POSIX)
766
767void SocketDispatcher::OnEvent(uint32_t ff, int err) {
768 // Make sure we deliver connect/accept first. Otherwise, consumers may see
769 // something like a READ followed by a CONNECT, which would be odd.
770 if ((ff & DE_CONNECT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700771 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800772 SignalConnectEvent(this);
773 }
774 if ((ff & DE_ACCEPT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700775 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800776 SignalReadEvent(this);
777 }
778 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700779 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800780 SignalReadEvent(this);
781 }
782 if ((ff & DE_WRITE) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700783 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800784 SignalWriteEvent(this);
785 }
786 if ((ff & DE_CLOSE) != 0) {
787 // The socket is now dead to us, so stop checking it.
jbauch577f5dc2017-05-17 16:32:26 -0700788 SetEnabledEvents(0);
jbauch4331fcd2016-01-06 22:20:28 -0800789 SignalCloseEvent(this, err);
790 }
791}
792
793#endif // WEBRTC_POSIX
794
795int SocketDispatcher::Close() {
796 if (s_ == INVALID_SOCKET)
797 return 0;
798
799#if defined(WEBRTC_WIN)
800 id_ = 0;
801 signal_close_ = false;
802#endif
803 ss_->Remove(this);
804 return PhysicalSocket::Close();
805}
806
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000807#if defined(WEBRTC_POSIX)
808class EventDispatcher : public Dispatcher {
809 public:
810 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
811 if (pipe(afd_) < 0)
812 LOG(LERROR) << "pipe failed";
813 ss_->Add(this);
814 }
815
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000816 ~EventDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000817 ss_->Remove(this);
818 close(afd_[0]);
819 close(afd_[1]);
820 }
821
822 virtual void Signal() {
823 CritScope cs(&crit_);
824 if (!fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200825 const uint8_t b[1] = {0};
nissec16fa5e2017-02-07 07:18:43 -0800826 const ssize_t res = write(afd_[1], b, sizeof(b));
827 RTC_DCHECK_EQ(1, res);
828 fSignaled_ = true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000829 }
830 }
831
Peter Boström0c4e06b2015-10-07 12:23:21 +0200832 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000833
Peter Boström0c4e06b2015-10-07 12:23:21 +0200834 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000835 // It is not possible to perfectly emulate an auto-resetting event with
836 // pipes. This simulates it by resetting before the event is handled.
837
838 CritScope cs(&crit_);
839 if (fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200840 uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
nissec16fa5e2017-02-07 07:18:43 -0800841 const ssize_t res = read(afd_[0], b, sizeof(b));
842 RTC_DCHECK_EQ(1, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000843 fSignaled_ = false;
844 }
845 }
846
nissec80e7412017-01-11 05:56:46 -0800847 void OnEvent(uint32_t ff, int err) override { RTC_NOTREACHED(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000848
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000849 int GetDescriptor() override { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000850
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000851 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000852
853 private:
854 PhysicalSocketServer *ss_;
855 int afd_[2];
856 bool fSignaled_;
857 CriticalSection crit_;
858};
859
860// These two classes use the self-pipe trick to deliver POSIX signals to our
861// select loop. This is the only safe, reliable, cross-platform way to do
862// non-trivial things with a POSIX signal in an event-driven program (until
863// proper pselect() implementations become ubiquitous).
864
865class PosixSignalHandler {
866 public:
867 // POSIX only specifies 32 signals, but in principle the system might have
868 // more and the programmer might choose to use them, so we size our array
869 // for 128.
870 static const int kNumPosixSignals = 128;
871
872 // There is just a single global instance. (Signal handlers do not get any
873 // sort of user-defined void * parameter, so they can't access anything that
874 // isn't global.)
875 static PosixSignalHandler* Instance() {
Andrew MacDonald469c2c02015-05-22 17:50:26 -0700876 RTC_DEFINE_STATIC_LOCAL(PosixSignalHandler, instance, ());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000877 return &instance;
878 }
879
880 // Returns true if the given signal number is set.
881 bool IsSignalSet(int signum) const {
nisseede5da42017-01-12 05:15:36 -0800882 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800883 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000884 return received_signal_[signum];
885 } else {
886 return false;
887 }
888 }
889
890 // Clears the given signal number.
891 void ClearSignal(int signum) {
nisseede5da42017-01-12 05:15:36 -0800892 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800893 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000894 received_signal_[signum] = false;
895 }
896 }
897
898 // Returns the file descriptor to monitor for signal events.
899 int GetDescriptor() const {
900 return afd_[0];
901 }
902
903 // This is called directly from our real signal handler, so it must be
904 // signal-handler-safe. That means it cannot assume anything about the
905 // user-level state of the process, since the handler could be executed at any
906 // time on any thread.
907 void OnPosixSignalReceived(int signum) {
tfarina5237aaf2015-11-10 23:44:30 -0800908 if (signum >= static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000909 // We don't have space in our array for this.
910 return;
911 }
912 // Set a flag saying we've seen this signal.
913 received_signal_[signum] = true;
914 // Notify application code that we got a signal.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200915 const uint8_t b[1] = {0};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000916 if (-1 == write(afd_[1], b, sizeof(b))) {
917 // Nothing we can do here. If there's an error somehow then there's
918 // nothing we can safely do from a signal handler.
919 // No, we can't even safely log it.
920 // But, we still have to check the return value here. Otherwise,
921 // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
922 return;
923 }
924 }
925
926 private:
927 PosixSignalHandler() {
928 if (pipe(afd_) < 0) {
929 LOG_ERR(LS_ERROR) << "pipe failed";
930 return;
931 }
932 if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
933 LOG_ERR(LS_WARNING) << "fcntl #1 failed";
934 }
935 if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
936 LOG_ERR(LS_WARNING) << "fcntl #2 failed";
937 }
938 memset(const_cast<void *>(static_cast<volatile void *>(received_signal_)),
939 0,
940 sizeof(received_signal_));
941 }
942
943 ~PosixSignalHandler() {
944 int fd1 = afd_[0];
945 int fd2 = afd_[1];
946 // We clobber the stored file descriptor numbers here or else in principle
947 // a signal that happens to be delivered during application termination
948 // could erroneously write a zero byte to an unrelated file handle in
949 // OnPosixSignalReceived() if some other file happens to be opened later
950 // during shutdown and happens to be given the same file descriptor number
951 // as our pipe had. Unfortunately even with this precaution there is still a
952 // race where that could occur if said signal happens to be handled
953 // concurrently with this code and happens to have already read the value of
954 // afd_[1] from memory before we clobber it, but that's unlikely.
955 afd_[0] = -1;
956 afd_[1] = -1;
957 close(fd1);
958 close(fd2);
959 }
960
961 int afd_[2];
962 // These are boolean flags that will be set in our signal handler and read
963 // and cleared from Wait(). There is a race involved in this, but it is
964 // benign. The signal handler sets the flag before signaling the pipe, so
965 // we'll never end up blocking in select() while a flag is still true.
966 // However, if two of the same signal arrive close to each other then it's
967 // possible that the second time the handler may set the flag while it's still
968 // true, meaning that signal will be missed. But the first occurrence of it
969 // will still be handled, so this isn't a problem.
970 // Volatile is not necessary here for correctness, but this data _is_ volatile
971 // so I've marked it as such.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200972 volatile uint8_t received_signal_[kNumPosixSignals];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000973};
974
975class PosixSignalDispatcher : public Dispatcher {
976 public:
977 PosixSignalDispatcher(PhysicalSocketServer *owner) : owner_(owner) {
978 owner_->Add(this);
979 }
980
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000981 ~PosixSignalDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000982 owner_->Remove(this);
983 }
984
Peter Boström0c4e06b2015-10-07 12:23:21 +0200985 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000986
Peter Boström0c4e06b2015-10-07 12:23:21 +0200987 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000988 // Events might get grouped if signals come very fast, so we read out up to
989 // 16 bytes to make sure we keep the pipe empty.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200990 uint8_t b[16];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000991 ssize_t ret = read(GetDescriptor(), b, sizeof(b));
992 if (ret < 0) {
993 LOG_ERR(LS_WARNING) << "Error in read()";
994 } else if (ret == 0) {
995 LOG(LS_WARNING) << "Should have read at least one byte";
996 }
997 }
998
Peter Boström0c4e06b2015-10-07 12:23:21 +0200999 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001000 for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
1001 ++signum) {
1002 if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
1003 PosixSignalHandler::Instance()->ClearSignal(signum);
1004 HandlerMap::iterator i = handlers_.find(signum);
1005 if (i == handlers_.end()) {
1006 // This can happen if a signal is delivered to our process at around
1007 // the same time as we unset our handler for it. It is not an error
1008 // condition, but it's unusual enough to be worth logging.
1009 LOG(LS_INFO) << "Received signal with no handler: " << signum;
1010 } else {
1011 // Otherwise, execute our handler.
1012 (*i->second)(signum);
1013 }
1014 }
1015 }
1016 }
1017
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001018 int GetDescriptor() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001019 return PosixSignalHandler::Instance()->GetDescriptor();
1020 }
1021
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001022 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001023
1024 void SetHandler(int signum, void (*handler)(int)) {
1025 handlers_[signum] = handler;
1026 }
1027
1028 void ClearHandler(int signum) {
1029 handlers_.erase(signum);
1030 }
1031
1032 bool HasHandlers() {
1033 return !handlers_.empty();
1034 }
1035
1036 private:
1037 typedef std::map<int, void (*)(int)> HandlerMap;
1038
1039 HandlerMap handlers_;
1040 // Our owner.
1041 PhysicalSocketServer *owner_;
1042};
1043
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001044#endif // WEBRTC_POSIX
1045
1046#if defined(WEBRTC_WIN)
Peter Boström0c4e06b2015-10-07 12:23:21 +02001047static uint32_t FlagsToEvents(uint32_t events) {
1048 uint32_t ffFD = FD_CLOSE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001049 if (events & DE_READ)
1050 ffFD |= FD_READ;
1051 if (events & DE_WRITE)
1052 ffFD |= FD_WRITE;
1053 if (events & DE_CONNECT)
1054 ffFD |= FD_CONNECT;
1055 if (events & DE_ACCEPT)
1056 ffFD |= FD_ACCEPT;
1057 return ffFD;
1058}
1059
1060class EventDispatcher : public Dispatcher {
1061 public:
1062 EventDispatcher(PhysicalSocketServer *ss) : ss_(ss) {
1063 hev_ = WSACreateEvent();
1064 if (hev_) {
1065 ss_->Add(this);
1066 }
1067 }
1068
1069 ~EventDispatcher() {
deadbeef37f5ecf2017-02-27 14:06:41 -08001070 if (hev_ != nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001071 ss_->Remove(this);
1072 WSACloseEvent(hev_);
deadbeef37f5ecf2017-02-27 14:06:41 -08001073 hev_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001074 }
1075 }
1076
1077 virtual void Signal() {
deadbeef37f5ecf2017-02-27 14:06:41 -08001078 if (hev_ != nullptr)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001079 WSASetEvent(hev_);
1080 }
1081
Peter Boström0c4e06b2015-10-07 12:23:21 +02001082 virtual uint32_t GetRequestedEvents() { return 0; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001083
Peter Boström0c4e06b2015-10-07 12:23:21 +02001084 virtual void OnPreEvent(uint32_t ff) { WSAResetEvent(hev_); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001085
Peter Boström0c4e06b2015-10-07 12:23:21 +02001086 virtual void OnEvent(uint32_t ff, int err) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001087
1088 virtual WSAEVENT GetWSAEvent() {
1089 return hev_;
1090 }
1091
1092 virtual SOCKET GetSocket() {
1093 return INVALID_SOCKET;
1094 }
1095
1096 virtual bool CheckSignalClose() { return false; }
1097
1098private:
1099 PhysicalSocketServer* ss_;
1100 WSAEVENT hev_;
1101};
honghaizcec0a082016-01-15 14:49:09 -08001102#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001103
1104// Sets the value of a boolean value to false when signaled.
1105class Signaler : public EventDispatcher {
1106 public:
1107 Signaler(PhysicalSocketServer* ss, bool* pf)
1108 : EventDispatcher(ss), pf_(pf) {
1109 }
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001110 ~Signaler() override { }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001111
Peter Boström0c4e06b2015-10-07 12:23:21 +02001112 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001113 if (pf_)
1114 *pf_ = false;
1115 }
1116
1117 private:
1118 bool *pf_;
1119};
1120
1121PhysicalSocketServer::PhysicalSocketServer()
1122 : fWait_(false) {
1123 signal_wakeup_ = new Signaler(this, &fWait_);
1124#if defined(WEBRTC_WIN)
1125 socket_ev_ = WSACreateEvent();
1126#endif
1127}
1128
1129PhysicalSocketServer::~PhysicalSocketServer() {
1130#if defined(WEBRTC_WIN)
1131 WSACloseEvent(socket_ev_);
1132#endif
1133#if defined(WEBRTC_POSIX)
1134 signal_dispatcher_.reset();
1135#endif
1136 delete signal_wakeup_;
nisseede5da42017-01-12 05:15:36 -08001137 RTC_DCHECK(dispatchers_.empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001138}
1139
1140void PhysicalSocketServer::WakeUp() {
1141 signal_wakeup_->Signal();
1142}
1143
1144Socket* PhysicalSocketServer::CreateSocket(int type) {
1145 return CreateSocket(AF_INET, type);
1146}
1147
1148Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
1149 PhysicalSocket* socket = new PhysicalSocket(this);
1150 if (socket->Create(family, type)) {
1151 return socket;
1152 } else {
1153 delete socket;
jbauch095ae152015-12-18 01:39:55 -08001154 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001155 }
1156}
1157
1158AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int type) {
1159 return CreateAsyncSocket(AF_INET, type);
1160}
1161
1162AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
1163 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1164 if (dispatcher->Create(family, type)) {
1165 return dispatcher;
1166 } else {
1167 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001168 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001169 }
1170}
1171
1172AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
1173 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1174 if (dispatcher->Initialize()) {
1175 return dispatcher;
1176 } else {
1177 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001178 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001179 }
1180}
1181
1182void PhysicalSocketServer::Add(Dispatcher *pdispatcher) {
1183 CritScope cs(&crit_);
1184 // Prevent duplicates. This can cause dead dispatchers to stick around.
1185 DispatcherList::iterator pos = std::find(dispatchers_.begin(),
1186 dispatchers_.end(),
1187 pdispatcher);
1188 if (pos != dispatchers_.end())
1189 return;
1190 dispatchers_.push_back(pdispatcher);
1191}
1192
1193void PhysicalSocketServer::Remove(Dispatcher *pdispatcher) {
1194 CritScope cs(&crit_);
1195 DispatcherList::iterator pos = std::find(dispatchers_.begin(),
1196 dispatchers_.end(),
1197 pdispatcher);
1198 // We silently ignore duplicate calls to Add, so we should silently ignore
1199 // the (expected) symmetric calls to Remove. Note that this may still hide
1200 // a real issue, so we at least log a warning about it.
1201 if (pos == dispatchers_.end()) {
1202 LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
1203 << "dispatcher, potentially from a duplicate call to Add.";
1204 return;
1205 }
1206 size_t index = pos - dispatchers_.begin();
1207 dispatchers_.erase(pos);
1208 for (IteratorList::iterator it = iterators_.begin(); it != iterators_.end();
1209 ++it) {
1210 if (index < **it) {
1211 --**it;
1212 }
1213 }
1214}
1215
1216#if defined(WEBRTC_POSIX)
1217bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
1218 // Calculate timing information
1219
deadbeef37f5ecf2017-02-27 14:06:41 -08001220 struct timeval* ptvWait = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001221 struct timeval tvWait;
1222 struct timeval tvStop;
1223 if (cmsWait != kForever) {
1224 // Calculate wait timeval
1225 tvWait.tv_sec = cmsWait / 1000;
1226 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1227 ptvWait = &tvWait;
1228
1229 // Calculate when to return in a timeval
deadbeef37f5ecf2017-02-27 14:06:41 -08001230 gettimeofday(&tvStop, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001231 tvStop.tv_sec += tvWait.tv_sec;
1232 tvStop.tv_usec += tvWait.tv_usec;
1233 if (tvStop.tv_usec >= 1000000) {
1234 tvStop.tv_usec -= 1000000;
1235 tvStop.tv_sec += 1;
1236 }
1237 }
1238
1239 // Zero all fd_sets. Don't need to do this inside the loop since
1240 // select() zeros the descriptors not signaled
1241
1242 fd_set fdsRead;
1243 FD_ZERO(&fdsRead);
1244 fd_set fdsWrite;
1245 FD_ZERO(&fdsWrite);
pbos@webrtc.org27e58982014-10-07 17:56:53 +00001246 // Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1247 // inline assembly in FD_ZERO.
1248 // http://crbug.com/344505
1249#ifdef MEMORY_SANITIZER
1250 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1251 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1252#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001253
1254 fWait_ = true;
1255
1256 while (fWait_) {
1257 int fdmax = -1;
1258 {
1259 CritScope cr(&crit_);
1260 for (size_t i = 0; i < dispatchers_.size(); ++i) {
1261 // Query dispatchers for read and write wait state
1262 Dispatcher *pdispatcher = dispatchers_[i];
nisseede5da42017-01-12 05:15:36 -08001263 RTC_DCHECK(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001264 if (!process_io && (pdispatcher != signal_wakeup_))
1265 continue;
1266 int fd = pdispatcher->GetDescriptor();
1267 if (fd > fdmax)
1268 fdmax = fd;
1269
Peter Boström0c4e06b2015-10-07 12:23:21 +02001270 uint32_t ff = pdispatcher->GetRequestedEvents();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001271 if (ff & (DE_READ | DE_ACCEPT))
1272 FD_SET(fd, &fdsRead);
1273 if (ff & (DE_WRITE | DE_CONNECT))
1274 FD_SET(fd, &fdsWrite);
1275 }
1276 }
1277
1278 // Wait then call handlers as appropriate
1279 // < 0 means error
1280 // 0 means timeout
1281 // > 0 means count of descriptors ready
deadbeef37f5ecf2017-02-27 14:06:41 -08001282 int n = select(fdmax + 1, &fdsRead, &fdsWrite, nullptr, ptvWait);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001283
1284 // If error, return error.
1285 if (n < 0) {
1286 if (errno != EINTR) {
1287 LOG_E(LS_ERROR, EN, errno) << "select";
1288 return false;
1289 }
1290 // Else ignore the error and keep going. If this EINTR was for one of the
1291 // signals managed by this PhysicalSocketServer, the
1292 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1293 // iteration.
1294 } else if (n == 0) {
1295 // If timeout, return success
1296 return true;
1297 } else {
1298 // We have signaled descriptors
1299 CritScope cr(&crit_);
1300 for (size_t i = 0; i < dispatchers_.size(); ++i) {
1301 Dispatcher *pdispatcher = dispatchers_[i];
1302 int fd = pdispatcher->GetDescriptor();
Peter Boström0c4e06b2015-10-07 12:23:21 +02001303 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001304 int errcode = 0;
1305
1306 // Reap any error code, which can be signaled through reads or writes.
jbauch095ae152015-12-18 01:39:55 -08001307 // TODO(pthatcher): Should we set errcode if getsockopt fails?
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001308 if (FD_ISSET(fd, &fdsRead) || FD_ISSET(fd, &fdsWrite)) {
1309 socklen_t len = sizeof(errcode);
1310 ::getsockopt(fd, SOL_SOCKET, SO_ERROR, &errcode, &len);
1311 }
1312
1313 // Check readable descriptors. If we're waiting on an accept, signal
1314 // that. Otherwise we're waiting for data, check to see if we're
1315 // readable or really closed.
jbauch095ae152015-12-18 01:39:55 -08001316 // TODO(pthatcher): Only peek at TCP descriptors.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001317 if (FD_ISSET(fd, &fdsRead)) {
1318 FD_CLR(fd, &fdsRead);
1319 if (pdispatcher->GetRequestedEvents() & DE_ACCEPT) {
1320 ff |= DE_ACCEPT;
1321 } else if (errcode || pdispatcher->IsDescriptorClosed()) {
1322 ff |= DE_CLOSE;
1323 } else {
1324 ff |= DE_READ;
1325 }
1326 }
1327
1328 // Check writable descriptors. If we're waiting on a connect, detect
1329 // success versus failure by the reaped error code.
1330 if (FD_ISSET(fd, &fdsWrite)) {
1331 FD_CLR(fd, &fdsWrite);
1332 if (pdispatcher->GetRequestedEvents() & DE_CONNECT) {
1333 if (!errcode) {
1334 ff |= DE_CONNECT;
1335 } else {
1336 ff |= DE_CLOSE;
1337 }
1338 } else {
1339 ff |= DE_WRITE;
1340 }
1341 }
1342
1343 // Tell the descriptor about the event.
1344 if (ff != 0) {
1345 pdispatcher->OnPreEvent(ff);
1346 pdispatcher->OnEvent(ff, errcode);
1347 }
1348 }
1349 }
1350
1351 // Recalc the time remaining to wait. Doing it here means it doesn't get
1352 // calced twice the first time through the loop
1353 if (ptvWait) {
1354 ptvWait->tv_sec = 0;
1355 ptvWait->tv_usec = 0;
1356 struct timeval tvT;
deadbeef37f5ecf2017-02-27 14:06:41 -08001357 gettimeofday(&tvT, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001358 if ((tvStop.tv_sec > tvT.tv_sec)
1359 || ((tvStop.tv_sec == tvT.tv_sec)
1360 && (tvStop.tv_usec > tvT.tv_usec))) {
1361 ptvWait->tv_sec = tvStop.tv_sec - tvT.tv_sec;
1362 ptvWait->tv_usec = tvStop.tv_usec - tvT.tv_usec;
1363 if (ptvWait->tv_usec < 0) {
nisseede5da42017-01-12 05:15:36 -08001364 RTC_DCHECK(ptvWait->tv_sec > 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001365 ptvWait->tv_usec += 1000000;
1366 ptvWait->tv_sec -= 1;
1367 }
1368 }
1369 }
1370 }
1371
1372 return true;
1373}
1374
1375static void GlobalSignalHandler(int signum) {
1376 PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
1377}
1378
1379bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
1380 void (*handler)(int)) {
1381 // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
1382 // otherwise set one.
1383 if (handler == SIG_IGN || handler == SIG_DFL) {
1384 if (!InstallSignal(signum, handler)) {
1385 return false;
1386 }
1387 if (signal_dispatcher_) {
1388 signal_dispatcher_->ClearHandler(signum);
1389 if (!signal_dispatcher_->HasHandlers()) {
1390 signal_dispatcher_.reset();
1391 }
1392 }
1393 } else {
1394 if (!signal_dispatcher_) {
1395 signal_dispatcher_.reset(new PosixSignalDispatcher(this));
1396 }
1397 signal_dispatcher_->SetHandler(signum, handler);
1398 if (!InstallSignal(signum, &GlobalSignalHandler)) {
1399 return false;
1400 }
1401 }
1402 return true;
1403}
1404
1405Dispatcher* PhysicalSocketServer::signal_dispatcher() {
1406 return signal_dispatcher_.get();
1407}
1408
1409bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
1410 struct sigaction act;
1411 // It doesn't really matter what we set this mask to.
1412 if (sigemptyset(&act.sa_mask) != 0) {
1413 LOG_ERR(LS_ERROR) << "Couldn't set mask";
1414 return false;
1415 }
1416 act.sa_handler = handler;
1417#if !defined(__native_client__)
1418 // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
1419 // and it's a nuisance. Though some syscalls still return EINTR and there's no
1420 // real standard for which ones. :(
1421 act.sa_flags = SA_RESTART;
1422#else
1423 act.sa_flags = 0;
1424#endif
deadbeef37f5ecf2017-02-27 14:06:41 -08001425 if (sigaction(signum, &act, nullptr) != 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001426 LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
1427 return false;
1428 }
1429 return true;
1430}
1431#endif // WEBRTC_POSIX
1432
1433#if defined(WEBRTC_WIN)
1434bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
Honghai Zhang82d78622016-05-06 11:29:15 -07001435 int64_t cmsTotal = cmsWait;
1436 int64_t cmsElapsed = 0;
1437 int64_t msStart = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001438
1439 fWait_ = true;
1440 while (fWait_) {
1441 std::vector<WSAEVENT> events;
1442 std::vector<Dispatcher *> event_owners;
1443
1444 events.push_back(socket_ev_);
1445
1446 {
1447 CritScope cr(&crit_);
1448 size_t i = 0;
1449 iterators_.push_back(&i);
1450 // Don't track dispatchers_.size(), because we want to pick up any new
1451 // dispatchers that were added while processing the loop.
1452 while (i < dispatchers_.size()) {
1453 Dispatcher* disp = dispatchers_[i++];
1454 if (!process_io && (disp != signal_wakeup_))
1455 continue;
1456 SOCKET s = disp->GetSocket();
1457 if (disp->CheckSignalClose()) {
1458 // We just signalled close, don't poll this socket
1459 } else if (s != INVALID_SOCKET) {
1460 WSAEventSelect(s,
1461 events[0],
1462 FlagsToEvents(disp->GetRequestedEvents()));
1463 } else {
1464 events.push_back(disp->GetWSAEvent());
1465 event_owners.push_back(disp);
1466 }
1467 }
nisseede5da42017-01-12 05:15:36 -08001468 RTC_DCHECK(iterators_.back() == &i);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001469 iterators_.pop_back();
1470 }
1471
1472 // Which is shorter, the delay wait or the asked wait?
1473
Honghai Zhang82d78622016-05-06 11:29:15 -07001474 int64_t cmsNext;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001475 if (cmsWait == kForever) {
1476 cmsNext = cmsWait;
1477 } else {
Honghai Zhang82d78622016-05-06 11:29:15 -07001478 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001479 }
1480
1481 // Wait for one of the events to signal
1482 DWORD dw = WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()),
1483 &events[0],
1484 false,
Honghai Zhang82d78622016-05-06 11:29:15 -07001485 static_cast<DWORD>(cmsNext),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001486 false);
1487
1488 if (dw == WSA_WAIT_FAILED) {
1489 // Failed?
jbauch095ae152015-12-18 01:39:55 -08001490 // TODO(pthatcher): need a better strategy than this!
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001491 WSAGetLastError();
nissec80e7412017-01-11 05:56:46 -08001492 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001493 return false;
1494 } else if (dw == WSA_WAIT_TIMEOUT) {
1495 // Timeout?
1496 return true;
1497 } else {
1498 // Figure out which one it is and call it
1499 CritScope cr(&crit_);
1500 int index = dw - WSA_WAIT_EVENT_0;
1501 if (index > 0) {
1502 --index; // The first event is the socket event
1503 event_owners[index]->OnPreEvent(0);
1504 event_owners[index]->OnEvent(0, 0);
1505 } else if (process_io) {
1506 size_t i = 0, end = dispatchers_.size();
1507 iterators_.push_back(&i);
1508 iterators_.push_back(&end); // Don't iterate over new dispatchers.
1509 while (i < end) {
1510 Dispatcher* disp = dispatchers_[i++];
1511 SOCKET s = disp->GetSocket();
1512 if (s == INVALID_SOCKET)
1513 continue;
1514
1515 WSANETWORKEVENTS wsaEvents;
1516 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1517 if (err == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001518 {
1519 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1520 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
1521 LOG(WARNING) << "PhysicalSocketServer got FD_READ_BIT error "
1522 << wsaEvents.iErrorCode[FD_READ_BIT];
1523 }
1524 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1525 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
1526 LOG(WARNING) << "PhysicalSocketServer got FD_WRITE_BIT error "
1527 << wsaEvents.iErrorCode[FD_WRITE_BIT];
1528 }
1529 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1530 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
1531 LOG(WARNING) << "PhysicalSocketServer got FD_CONNECT_BIT error "
1532 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
1533 }
1534 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1535 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
1536 LOG(WARNING) << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1537 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
1538 }
1539 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1540 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
1541 LOG(WARNING) << "PhysicalSocketServer got FD_CLOSE_BIT error "
1542 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
1543 }
1544 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001545 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001546 int errcode = 0;
1547 if (wsaEvents.lNetworkEvents & FD_READ)
1548 ff |= DE_READ;
1549 if (wsaEvents.lNetworkEvents & FD_WRITE)
1550 ff |= DE_WRITE;
1551 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1552 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1553 ff |= DE_CONNECT;
1554 } else {
1555 ff |= DE_CLOSE;
1556 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1557 }
1558 }
1559 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1560 ff |= DE_ACCEPT;
1561 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1562 ff |= DE_CLOSE;
1563 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1564 }
1565 if (ff != 0) {
1566 disp->OnPreEvent(ff);
1567 disp->OnEvent(ff, errcode);
1568 }
1569 }
1570 }
nisseede5da42017-01-12 05:15:36 -08001571 RTC_DCHECK(iterators_.back() == &end);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001572 iterators_.pop_back();
nisseede5da42017-01-12 05:15:36 -08001573 RTC_DCHECK(iterators_.back() == &i);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001574 iterators_.pop_back();
1575 }
1576
1577 // Reset the network event until new activity occurs
1578 WSAResetEvent(socket_ev_);
1579 }
1580
1581 // Break?
1582 if (!fWait_)
1583 break;
1584 cmsElapsed = TimeSince(msStart);
1585 if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
1586 break;
1587 }
1588 }
1589
1590 // Done
1591 return true;
1592}
honghaizcec0a082016-01-15 14:49:09 -08001593#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001594
1595} // namespace rtc