blob: 4ab33fb673a1154e01a3eb58f45d136a4f9fd523 [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
deadbeefeae45642017-05-26 16:27:09 -0700612#if defined(WEBRTC_IOS)
613 // iOS may kill sockets when the app is moved to the background
614 // (specifically, if the app doesn't use the "voip" UIBackgroundMode). When
615 // we attempt to write to such a socket, SIGPIPE will be raised, which by
616 // default will terminate the process, which we don't want. By specifying
617 // this socket option, SIGPIPE will be disabled for the socket.
618 int value = 1;
619 ::setsockopt(s_, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value));
620#endif
jbauch4331fcd2016-01-06 22:20:28 -0800621 ss_->Add(this);
622 return true;
623}
624
625bool SocketDispatcher::Create(int type) {
626 return Create(AF_INET, type);
627}
628
629bool SocketDispatcher::Create(int family, int type) {
630 // Change the socket to be non-blocking.
631 if (!PhysicalSocket::Create(family, type))
632 return false;
633
634 if (!Initialize())
635 return false;
636
637#if defined(WEBRTC_WIN)
638 do { id_ = ++next_id_; } while (id_ == 0);
639#endif
640 return true;
641}
642
643#if defined(WEBRTC_WIN)
644
645WSAEVENT SocketDispatcher::GetWSAEvent() {
646 return WSA_INVALID_EVENT;
647}
648
649SOCKET SocketDispatcher::GetSocket() {
650 return s_;
651}
652
653bool SocketDispatcher::CheckSignalClose() {
654 if (!signal_close_)
655 return false;
656
657 char ch;
658 if (recv(s_, &ch, 1, MSG_PEEK) > 0)
659 return false;
660
661 state_ = CS_CLOSED;
662 signal_close_ = false;
663 SignalCloseEvent(this, signal_err_);
664 return true;
665}
666
667int SocketDispatcher::next_id_ = 0;
668
669#elif defined(WEBRTC_POSIX)
670
671int SocketDispatcher::GetDescriptor() {
672 return s_;
673}
674
675bool SocketDispatcher::IsDescriptorClosed() {
deadbeeffaedf7f2017-02-09 15:09:22 -0800676 if (udp_) {
677 // The MSG_PEEK trick doesn't work for UDP, since (at least in some
678 // circumstances) it requires reading an entire UDP packet, which would be
679 // bad for performance here. So, just check whether |s_| has been closed,
680 // which should be sufficient.
681 return s_ == INVALID_SOCKET;
682 }
jbauch4331fcd2016-01-06 22:20:28 -0800683 // We don't have a reliable way of distinguishing end-of-stream
684 // from readability. So test on each readable call. Is this
685 // inefficient? Probably.
686 char ch;
687 ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
688 if (res > 0) {
689 // Data available, so not closed.
690 return false;
691 } else if (res == 0) {
692 // EOF, so closed.
693 return true;
694 } else { // error
695 switch (errno) {
696 // Returned if we've already closed s_.
697 case EBADF:
698 // Returned during ungraceful peer shutdown.
699 case ECONNRESET:
700 return true;
deadbeeffaedf7f2017-02-09 15:09:22 -0800701 // The normal blocking error; don't log anything.
702 case EWOULDBLOCK:
703 // Interrupted system call.
704 case EINTR:
705 return false;
jbauch4331fcd2016-01-06 22:20:28 -0800706 default:
707 // Assume that all other errors are just blocking errors, meaning the
708 // connection is still good but we just can't read from it right now.
709 // This should only happen when connecting (and at most once), because
710 // in all other cases this function is only called if the file
711 // descriptor is already known to be in the readable state. However,
712 // it's not necessary a problem if we spuriously interpret a
713 // "connection lost"-type error as a blocking error, because typically
714 // the next recv() will get EOF, so we'll still eventually notice that
715 // the socket is closed.
716 LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
717 return false;
718 }
719 }
720}
721
722#endif // WEBRTC_POSIX
723
724uint32_t SocketDispatcher::GetRequestedEvents() {
jbauch577f5dc2017-05-17 16:32:26 -0700725 return enabled_events();
jbauch4331fcd2016-01-06 22:20:28 -0800726}
727
728void SocketDispatcher::OnPreEvent(uint32_t ff) {
729 if ((ff & DE_CONNECT) != 0)
730 state_ = CS_CONNECTED;
731
732#if defined(WEBRTC_WIN)
733 // We set CS_CLOSED from CheckSignalClose.
734#elif defined(WEBRTC_POSIX)
735 if ((ff & DE_CLOSE) != 0)
736 state_ = CS_CLOSED;
737#endif
738}
739
740#if defined(WEBRTC_WIN)
741
742void SocketDispatcher::OnEvent(uint32_t ff, int err) {
743 int cache_id = id_;
744 // Make sure we deliver connect/accept first. Otherwise, consumers may see
745 // something like a READ followed by a CONNECT, which would be odd.
746 if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
747 if (ff != DE_CONNECT)
748 LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
jbauch577f5dc2017-05-17 16:32:26 -0700749 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800750#if !defined(NDEBUG)
751 dbg_addr_ = "Connected @ ";
752 dbg_addr_.append(GetRemoteAddress().ToString());
753#endif
754 SignalConnectEvent(this);
755 }
756 if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700757 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800758 SignalReadEvent(this);
759 }
760 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700761 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800762 SignalReadEvent(this);
763 }
764 if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
jbauch577f5dc2017-05-17 16:32:26 -0700765 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800766 SignalWriteEvent(this);
767 }
768 if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
769 signal_close_ = true;
770 signal_err_ = err;
771 }
772}
773
774#elif defined(WEBRTC_POSIX)
775
776void SocketDispatcher::OnEvent(uint32_t ff, int err) {
777 // Make sure we deliver connect/accept first. Otherwise, consumers may see
778 // something like a READ followed by a CONNECT, which would be odd.
779 if ((ff & DE_CONNECT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700780 DisableEvents(DE_CONNECT);
jbauch4331fcd2016-01-06 22:20:28 -0800781 SignalConnectEvent(this);
782 }
783 if ((ff & DE_ACCEPT) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700784 DisableEvents(DE_ACCEPT);
jbauch4331fcd2016-01-06 22:20:28 -0800785 SignalReadEvent(this);
786 }
787 if ((ff & DE_READ) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700788 DisableEvents(DE_READ);
jbauch4331fcd2016-01-06 22:20:28 -0800789 SignalReadEvent(this);
790 }
791 if ((ff & DE_WRITE) != 0) {
jbauch577f5dc2017-05-17 16:32:26 -0700792 DisableEvents(DE_WRITE);
jbauch4331fcd2016-01-06 22:20:28 -0800793 SignalWriteEvent(this);
794 }
795 if ((ff & DE_CLOSE) != 0) {
796 // The socket is now dead to us, so stop checking it.
jbauch577f5dc2017-05-17 16:32:26 -0700797 SetEnabledEvents(0);
jbauch4331fcd2016-01-06 22:20:28 -0800798 SignalCloseEvent(this, err);
799 }
800}
801
802#endif // WEBRTC_POSIX
803
804int SocketDispatcher::Close() {
805 if (s_ == INVALID_SOCKET)
806 return 0;
807
808#if defined(WEBRTC_WIN)
809 id_ = 0;
810 signal_close_ = false;
811#endif
812 ss_->Remove(this);
813 return PhysicalSocket::Close();
814}
815
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000816#if defined(WEBRTC_POSIX)
817class EventDispatcher : public Dispatcher {
818 public:
819 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
820 if (pipe(afd_) < 0)
821 LOG(LERROR) << "pipe failed";
822 ss_->Add(this);
823 }
824
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000825 ~EventDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000826 ss_->Remove(this);
827 close(afd_[0]);
828 close(afd_[1]);
829 }
830
831 virtual void Signal() {
832 CritScope cs(&crit_);
833 if (!fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200834 const uint8_t b[1] = {0};
nissec16fa5e2017-02-07 07:18:43 -0800835 const ssize_t res = write(afd_[1], b, sizeof(b));
836 RTC_DCHECK_EQ(1, res);
837 fSignaled_ = true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000838 }
839 }
840
Peter Boström0c4e06b2015-10-07 12:23:21 +0200841 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000842
Peter Boström0c4e06b2015-10-07 12:23:21 +0200843 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000844 // It is not possible to perfectly emulate an auto-resetting event with
845 // pipes. This simulates it by resetting before the event is handled.
846
847 CritScope cs(&crit_);
848 if (fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200849 uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
nissec16fa5e2017-02-07 07:18:43 -0800850 const ssize_t res = read(afd_[0], b, sizeof(b));
851 RTC_DCHECK_EQ(1, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000852 fSignaled_ = false;
853 }
854 }
855
nissec80e7412017-01-11 05:56:46 -0800856 void OnEvent(uint32_t ff, int err) override { RTC_NOTREACHED(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000857
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000858 int GetDescriptor() override { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000859
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000860 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000861
862 private:
863 PhysicalSocketServer *ss_;
864 int afd_[2];
865 bool fSignaled_;
866 CriticalSection crit_;
867};
868
869// These two classes use the self-pipe trick to deliver POSIX signals to our
870// select loop. This is the only safe, reliable, cross-platform way to do
871// non-trivial things with a POSIX signal in an event-driven program (until
872// proper pselect() implementations become ubiquitous).
873
874class PosixSignalHandler {
875 public:
876 // POSIX only specifies 32 signals, but in principle the system might have
877 // more and the programmer might choose to use them, so we size our array
878 // for 128.
879 static const int kNumPosixSignals = 128;
880
881 // There is just a single global instance. (Signal handlers do not get any
882 // sort of user-defined void * parameter, so they can't access anything that
883 // isn't global.)
884 static PosixSignalHandler* Instance() {
Andrew MacDonald469c2c02015-05-22 17:50:26 -0700885 RTC_DEFINE_STATIC_LOCAL(PosixSignalHandler, instance, ());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000886 return &instance;
887 }
888
889 // Returns true if the given signal number is set.
890 bool IsSignalSet(int signum) const {
nisseede5da42017-01-12 05:15:36 -0800891 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800892 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000893 return received_signal_[signum];
894 } else {
895 return false;
896 }
897 }
898
899 // Clears the given signal number.
900 void ClearSignal(int signum) {
nisseede5da42017-01-12 05:15:36 -0800901 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800902 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000903 received_signal_[signum] = false;
904 }
905 }
906
907 // Returns the file descriptor to monitor for signal events.
908 int GetDescriptor() const {
909 return afd_[0];
910 }
911
912 // This is called directly from our real signal handler, so it must be
913 // signal-handler-safe. That means it cannot assume anything about the
914 // user-level state of the process, since the handler could be executed at any
915 // time on any thread.
916 void OnPosixSignalReceived(int signum) {
tfarina5237aaf2015-11-10 23:44:30 -0800917 if (signum >= static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000918 // We don't have space in our array for this.
919 return;
920 }
921 // Set a flag saying we've seen this signal.
922 received_signal_[signum] = true;
923 // Notify application code that we got a signal.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200924 const uint8_t b[1] = {0};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000925 if (-1 == write(afd_[1], b, sizeof(b))) {
926 // Nothing we can do here. If there's an error somehow then there's
927 // nothing we can safely do from a signal handler.
928 // No, we can't even safely log it.
929 // But, we still have to check the return value here. Otherwise,
930 // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
931 return;
932 }
933 }
934
935 private:
936 PosixSignalHandler() {
937 if (pipe(afd_) < 0) {
938 LOG_ERR(LS_ERROR) << "pipe failed";
939 return;
940 }
941 if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
942 LOG_ERR(LS_WARNING) << "fcntl #1 failed";
943 }
944 if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
945 LOG_ERR(LS_WARNING) << "fcntl #2 failed";
946 }
947 memset(const_cast<void *>(static_cast<volatile void *>(received_signal_)),
948 0,
949 sizeof(received_signal_));
950 }
951
952 ~PosixSignalHandler() {
953 int fd1 = afd_[0];
954 int fd2 = afd_[1];
955 // We clobber the stored file descriptor numbers here or else in principle
956 // a signal that happens to be delivered during application termination
957 // could erroneously write a zero byte to an unrelated file handle in
958 // OnPosixSignalReceived() if some other file happens to be opened later
959 // during shutdown and happens to be given the same file descriptor number
960 // as our pipe had. Unfortunately even with this precaution there is still a
961 // race where that could occur if said signal happens to be handled
962 // concurrently with this code and happens to have already read the value of
963 // afd_[1] from memory before we clobber it, but that's unlikely.
964 afd_[0] = -1;
965 afd_[1] = -1;
966 close(fd1);
967 close(fd2);
968 }
969
970 int afd_[2];
971 // These are boolean flags that will be set in our signal handler and read
972 // and cleared from Wait(). There is a race involved in this, but it is
973 // benign. The signal handler sets the flag before signaling the pipe, so
974 // we'll never end up blocking in select() while a flag is still true.
975 // However, if two of the same signal arrive close to each other then it's
976 // possible that the second time the handler may set the flag while it's still
977 // true, meaning that signal will be missed. But the first occurrence of it
978 // will still be handled, so this isn't a problem.
979 // Volatile is not necessary here for correctness, but this data _is_ volatile
980 // so I've marked it as such.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200981 volatile uint8_t received_signal_[kNumPosixSignals];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000982};
983
984class PosixSignalDispatcher : public Dispatcher {
985 public:
986 PosixSignalDispatcher(PhysicalSocketServer *owner) : owner_(owner) {
987 owner_->Add(this);
988 }
989
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000990 ~PosixSignalDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000991 owner_->Remove(this);
992 }
993
Peter Boström0c4e06b2015-10-07 12:23:21 +0200994 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000995
Peter Boström0c4e06b2015-10-07 12:23:21 +0200996 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000997 // Events might get grouped if signals come very fast, so we read out up to
998 // 16 bytes to make sure we keep the pipe empty.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200999 uint8_t b[16];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001000 ssize_t ret = read(GetDescriptor(), b, sizeof(b));
1001 if (ret < 0) {
1002 LOG_ERR(LS_WARNING) << "Error in read()";
1003 } else if (ret == 0) {
1004 LOG(LS_WARNING) << "Should have read at least one byte";
1005 }
1006 }
1007
Peter Boström0c4e06b2015-10-07 12:23:21 +02001008 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001009 for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
1010 ++signum) {
1011 if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
1012 PosixSignalHandler::Instance()->ClearSignal(signum);
1013 HandlerMap::iterator i = handlers_.find(signum);
1014 if (i == handlers_.end()) {
1015 // This can happen if a signal is delivered to our process at around
1016 // the same time as we unset our handler for it. It is not an error
1017 // condition, but it's unusual enough to be worth logging.
1018 LOG(LS_INFO) << "Received signal with no handler: " << signum;
1019 } else {
1020 // Otherwise, execute our handler.
1021 (*i->second)(signum);
1022 }
1023 }
1024 }
1025 }
1026
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001027 int GetDescriptor() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001028 return PosixSignalHandler::Instance()->GetDescriptor();
1029 }
1030
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001031 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001032
1033 void SetHandler(int signum, void (*handler)(int)) {
1034 handlers_[signum] = handler;
1035 }
1036
1037 void ClearHandler(int signum) {
1038 handlers_.erase(signum);
1039 }
1040
1041 bool HasHandlers() {
1042 return !handlers_.empty();
1043 }
1044
1045 private:
1046 typedef std::map<int, void (*)(int)> HandlerMap;
1047
1048 HandlerMap handlers_;
1049 // Our owner.
1050 PhysicalSocketServer *owner_;
1051};
1052
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001053#endif // WEBRTC_POSIX
1054
1055#if defined(WEBRTC_WIN)
Peter Boström0c4e06b2015-10-07 12:23:21 +02001056static uint32_t FlagsToEvents(uint32_t events) {
1057 uint32_t ffFD = FD_CLOSE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001058 if (events & DE_READ)
1059 ffFD |= FD_READ;
1060 if (events & DE_WRITE)
1061 ffFD |= FD_WRITE;
1062 if (events & DE_CONNECT)
1063 ffFD |= FD_CONNECT;
1064 if (events & DE_ACCEPT)
1065 ffFD |= FD_ACCEPT;
1066 return ffFD;
1067}
1068
1069class EventDispatcher : public Dispatcher {
1070 public:
1071 EventDispatcher(PhysicalSocketServer *ss) : ss_(ss) {
1072 hev_ = WSACreateEvent();
1073 if (hev_) {
1074 ss_->Add(this);
1075 }
1076 }
1077
1078 ~EventDispatcher() {
deadbeef37f5ecf2017-02-27 14:06:41 -08001079 if (hev_ != nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001080 ss_->Remove(this);
1081 WSACloseEvent(hev_);
deadbeef37f5ecf2017-02-27 14:06:41 -08001082 hev_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001083 }
1084 }
1085
1086 virtual void Signal() {
deadbeef37f5ecf2017-02-27 14:06:41 -08001087 if (hev_ != nullptr)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001088 WSASetEvent(hev_);
1089 }
1090
Peter Boström0c4e06b2015-10-07 12:23:21 +02001091 virtual uint32_t GetRequestedEvents() { return 0; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001092
Peter Boström0c4e06b2015-10-07 12:23:21 +02001093 virtual void OnPreEvent(uint32_t ff) { WSAResetEvent(hev_); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001094
Peter Boström0c4e06b2015-10-07 12:23:21 +02001095 virtual void OnEvent(uint32_t ff, int err) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001096
1097 virtual WSAEVENT GetWSAEvent() {
1098 return hev_;
1099 }
1100
1101 virtual SOCKET GetSocket() {
1102 return INVALID_SOCKET;
1103 }
1104
1105 virtual bool CheckSignalClose() { return false; }
1106
1107private:
1108 PhysicalSocketServer* ss_;
1109 WSAEVENT hev_;
1110};
honghaizcec0a082016-01-15 14:49:09 -08001111#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001112
1113// Sets the value of a boolean value to false when signaled.
1114class Signaler : public EventDispatcher {
1115 public:
1116 Signaler(PhysicalSocketServer* ss, bool* pf)
1117 : EventDispatcher(ss), pf_(pf) {
1118 }
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001119 ~Signaler() override { }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001120
Peter Boström0c4e06b2015-10-07 12:23:21 +02001121 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001122 if (pf_)
1123 *pf_ = false;
1124 }
1125
1126 private:
1127 bool *pf_;
1128};
1129
1130PhysicalSocketServer::PhysicalSocketServer()
1131 : fWait_(false) {
1132 signal_wakeup_ = new Signaler(this, &fWait_);
1133#if defined(WEBRTC_WIN)
1134 socket_ev_ = WSACreateEvent();
1135#endif
1136}
1137
1138PhysicalSocketServer::~PhysicalSocketServer() {
1139#if defined(WEBRTC_WIN)
1140 WSACloseEvent(socket_ev_);
1141#endif
1142#if defined(WEBRTC_POSIX)
1143 signal_dispatcher_.reset();
1144#endif
1145 delete signal_wakeup_;
nisseede5da42017-01-12 05:15:36 -08001146 RTC_DCHECK(dispatchers_.empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001147}
1148
1149void PhysicalSocketServer::WakeUp() {
1150 signal_wakeup_->Signal();
1151}
1152
1153Socket* PhysicalSocketServer::CreateSocket(int type) {
1154 return CreateSocket(AF_INET, type);
1155}
1156
1157Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
1158 PhysicalSocket* socket = new PhysicalSocket(this);
1159 if (socket->Create(family, type)) {
1160 return socket;
1161 } else {
1162 delete socket;
jbauch095ae152015-12-18 01:39:55 -08001163 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001164 }
1165}
1166
1167AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int type) {
1168 return CreateAsyncSocket(AF_INET, type);
1169}
1170
1171AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
1172 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1173 if (dispatcher->Create(family, type)) {
1174 return dispatcher;
1175 } else {
1176 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001177 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001178 }
1179}
1180
1181AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
1182 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1183 if (dispatcher->Initialize()) {
1184 return dispatcher;
1185 } else {
1186 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001187 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001188 }
1189}
1190
1191void PhysicalSocketServer::Add(Dispatcher *pdispatcher) {
1192 CritScope cs(&crit_);
1193 // Prevent duplicates. This can cause dead dispatchers to stick around.
1194 DispatcherList::iterator pos = std::find(dispatchers_.begin(),
1195 dispatchers_.end(),
1196 pdispatcher);
1197 if (pos != dispatchers_.end())
1198 return;
1199 dispatchers_.push_back(pdispatcher);
1200}
1201
1202void PhysicalSocketServer::Remove(Dispatcher *pdispatcher) {
1203 CritScope cs(&crit_);
1204 DispatcherList::iterator pos = std::find(dispatchers_.begin(),
1205 dispatchers_.end(),
1206 pdispatcher);
1207 // We silently ignore duplicate calls to Add, so we should silently ignore
1208 // the (expected) symmetric calls to Remove. Note that this may still hide
1209 // a real issue, so we at least log a warning about it.
1210 if (pos == dispatchers_.end()) {
1211 LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
1212 << "dispatcher, potentially from a duplicate call to Add.";
1213 return;
1214 }
1215 size_t index = pos - dispatchers_.begin();
1216 dispatchers_.erase(pos);
1217 for (IteratorList::iterator it = iterators_.begin(); it != iterators_.end();
1218 ++it) {
1219 if (index < **it) {
1220 --**it;
1221 }
1222 }
1223}
1224
1225#if defined(WEBRTC_POSIX)
1226bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
1227 // Calculate timing information
1228
deadbeef37f5ecf2017-02-27 14:06:41 -08001229 struct timeval* ptvWait = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001230 struct timeval tvWait;
1231 struct timeval tvStop;
1232 if (cmsWait != kForever) {
1233 // Calculate wait timeval
1234 tvWait.tv_sec = cmsWait / 1000;
1235 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1236 ptvWait = &tvWait;
1237
1238 // Calculate when to return in a timeval
deadbeef37f5ecf2017-02-27 14:06:41 -08001239 gettimeofday(&tvStop, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001240 tvStop.tv_sec += tvWait.tv_sec;
1241 tvStop.tv_usec += tvWait.tv_usec;
1242 if (tvStop.tv_usec >= 1000000) {
1243 tvStop.tv_usec -= 1000000;
1244 tvStop.tv_sec += 1;
1245 }
1246 }
1247
1248 // Zero all fd_sets. Don't need to do this inside the loop since
1249 // select() zeros the descriptors not signaled
1250
1251 fd_set fdsRead;
1252 FD_ZERO(&fdsRead);
1253 fd_set fdsWrite;
1254 FD_ZERO(&fdsWrite);
pbos@webrtc.org27e58982014-10-07 17:56:53 +00001255 // Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1256 // inline assembly in FD_ZERO.
1257 // http://crbug.com/344505
1258#ifdef MEMORY_SANITIZER
1259 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1260 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1261#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001262
1263 fWait_ = true;
1264
1265 while (fWait_) {
1266 int fdmax = -1;
1267 {
1268 CritScope cr(&crit_);
1269 for (size_t i = 0; i < dispatchers_.size(); ++i) {
1270 // Query dispatchers for read and write wait state
1271 Dispatcher *pdispatcher = dispatchers_[i];
nisseede5da42017-01-12 05:15:36 -08001272 RTC_DCHECK(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001273 if (!process_io && (pdispatcher != signal_wakeup_))
1274 continue;
1275 int fd = pdispatcher->GetDescriptor();
1276 if (fd > fdmax)
1277 fdmax = fd;
1278
Peter Boström0c4e06b2015-10-07 12:23:21 +02001279 uint32_t ff = pdispatcher->GetRequestedEvents();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001280 if (ff & (DE_READ | DE_ACCEPT))
1281 FD_SET(fd, &fdsRead);
1282 if (ff & (DE_WRITE | DE_CONNECT))
1283 FD_SET(fd, &fdsWrite);
1284 }
1285 }
1286
1287 // Wait then call handlers as appropriate
1288 // < 0 means error
1289 // 0 means timeout
1290 // > 0 means count of descriptors ready
deadbeef37f5ecf2017-02-27 14:06:41 -08001291 int n = select(fdmax + 1, &fdsRead, &fdsWrite, nullptr, ptvWait);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001292
1293 // If error, return error.
1294 if (n < 0) {
1295 if (errno != EINTR) {
1296 LOG_E(LS_ERROR, EN, errno) << "select";
1297 return false;
1298 }
1299 // Else ignore the error and keep going. If this EINTR was for one of the
1300 // signals managed by this PhysicalSocketServer, the
1301 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1302 // iteration.
1303 } else if (n == 0) {
1304 // If timeout, return success
1305 return true;
1306 } else {
1307 // We have signaled descriptors
1308 CritScope cr(&crit_);
1309 for (size_t i = 0; i < dispatchers_.size(); ++i) {
1310 Dispatcher *pdispatcher = dispatchers_[i];
1311 int fd = pdispatcher->GetDescriptor();
Peter Boström0c4e06b2015-10-07 12:23:21 +02001312 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001313 int errcode = 0;
1314
1315 // Reap any error code, which can be signaled through reads or writes.
jbauch095ae152015-12-18 01:39:55 -08001316 // TODO(pthatcher): Should we set errcode if getsockopt fails?
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001317 if (FD_ISSET(fd, &fdsRead) || FD_ISSET(fd, &fdsWrite)) {
1318 socklen_t len = sizeof(errcode);
1319 ::getsockopt(fd, SOL_SOCKET, SO_ERROR, &errcode, &len);
1320 }
1321
1322 // Check readable descriptors. If we're waiting on an accept, signal
1323 // that. Otherwise we're waiting for data, check to see if we're
1324 // readable or really closed.
jbauch095ae152015-12-18 01:39:55 -08001325 // TODO(pthatcher): Only peek at TCP descriptors.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001326 if (FD_ISSET(fd, &fdsRead)) {
1327 FD_CLR(fd, &fdsRead);
1328 if (pdispatcher->GetRequestedEvents() & DE_ACCEPT) {
1329 ff |= DE_ACCEPT;
1330 } else if (errcode || pdispatcher->IsDescriptorClosed()) {
1331 ff |= DE_CLOSE;
1332 } else {
1333 ff |= DE_READ;
1334 }
1335 }
1336
1337 // Check writable descriptors. If we're waiting on a connect, detect
1338 // success versus failure by the reaped error code.
1339 if (FD_ISSET(fd, &fdsWrite)) {
1340 FD_CLR(fd, &fdsWrite);
1341 if (pdispatcher->GetRequestedEvents() & DE_CONNECT) {
1342 if (!errcode) {
1343 ff |= DE_CONNECT;
1344 } else {
1345 ff |= DE_CLOSE;
1346 }
1347 } else {
1348 ff |= DE_WRITE;
1349 }
1350 }
1351
1352 // Tell the descriptor about the event.
1353 if (ff != 0) {
1354 pdispatcher->OnPreEvent(ff);
1355 pdispatcher->OnEvent(ff, errcode);
1356 }
1357 }
1358 }
1359
1360 // Recalc the time remaining to wait. Doing it here means it doesn't get
1361 // calced twice the first time through the loop
1362 if (ptvWait) {
1363 ptvWait->tv_sec = 0;
1364 ptvWait->tv_usec = 0;
1365 struct timeval tvT;
deadbeef37f5ecf2017-02-27 14:06:41 -08001366 gettimeofday(&tvT, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001367 if ((tvStop.tv_sec > tvT.tv_sec)
1368 || ((tvStop.tv_sec == tvT.tv_sec)
1369 && (tvStop.tv_usec > tvT.tv_usec))) {
1370 ptvWait->tv_sec = tvStop.tv_sec - tvT.tv_sec;
1371 ptvWait->tv_usec = tvStop.tv_usec - tvT.tv_usec;
1372 if (ptvWait->tv_usec < 0) {
nisseede5da42017-01-12 05:15:36 -08001373 RTC_DCHECK(ptvWait->tv_sec > 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001374 ptvWait->tv_usec += 1000000;
1375 ptvWait->tv_sec -= 1;
1376 }
1377 }
1378 }
1379 }
1380
1381 return true;
1382}
1383
1384static void GlobalSignalHandler(int signum) {
1385 PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
1386}
1387
1388bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
1389 void (*handler)(int)) {
1390 // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
1391 // otherwise set one.
1392 if (handler == SIG_IGN || handler == SIG_DFL) {
1393 if (!InstallSignal(signum, handler)) {
1394 return false;
1395 }
1396 if (signal_dispatcher_) {
1397 signal_dispatcher_->ClearHandler(signum);
1398 if (!signal_dispatcher_->HasHandlers()) {
1399 signal_dispatcher_.reset();
1400 }
1401 }
1402 } else {
1403 if (!signal_dispatcher_) {
1404 signal_dispatcher_.reset(new PosixSignalDispatcher(this));
1405 }
1406 signal_dispatcher_->SetHandler(signum, handler);
1407 if (!InstallSignal(signum, &GlobalSignalHandler)) {
1408 return false;
1409 }
1410 }
1411 return true;
1412}
1413
1414Dispatcher* PhysicalSocketServer::signal_dispatcher() {
1415 return signal_dispatcher_.get();
1416}
1417
1418bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
1419 struct sigaction act;
1420 // It doesn't really matter what we set this mask to.
1421 if (sigemptyset(&act.sa_mask) != 0) {
1422 LOG_ERR(LS_ERROR) << "Couldn't set mask";
1423 return false;
1424 }
1425 act.sa_handler = handler;
1426#if !defined(__native_client__)
1427 // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
1428 // and it's a nuisance. Though some syscalls still return EINTR and there's no
1429 // real standard for which ones. :(
1430 act.sa_flags = SA_RESTART;
1431#else
1432 act.sa_flags = 0;
1433#endif
deadbeef37f5ecf2017-02-27 14:06:41 -08001434 if (sigaction(signum, &act, nullptr) != 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001435 LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
1436 return false;
1437 }
1438 return true;
1439}
1440#endif // WEBRTC_POSIX
1441
1442#if defined(WEBRTC_WIN)
1443bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
Honghai Zhang82d78622016-05-06 11:29:15 -07001444 int64_t cmsTotal = cmsWait;
1445 int64_t cmsElapsed = 0;
1446 int64_t msStart = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001447
1448 fWait_ = true;
1449 while (fWait_) {
1450 std::vector<WSAEVENT> events;
1451 std::vector<Dispatcher *> event_owners;
1452
1453 events.push_back(socket_ev_);
1454
1455 {
1456 CritScope cr(&crit_);
1457 size_t i = 0;
1458 iterators_.push_back(&i);
1459 // Don't track dispatchers_.size(), because we want to pick up any new
1460 // dispatchers that were added while processing the loop.
1461 while (i < dispatchers_.size()) {
1462 Dispatcher* disp = dispatchers_[i++];
1463 if (!process_io && (disp != signal_wakeup_))
1464 continue;
1465 SOCKET s = disp->GetSocket();
1466 if (disp->CheckSignalClose()) {
1467 // We just signalled close, don't poll this socket
1468 } else if (s != INVALID_SOCKET) {
1469 WSAEventSelect(s,
1470 events[0],
1471 FlagsToEvents(disp->GetRequestedEvents()));
1472 } else {
1473 events.push_back(disp->GetWSAEvent());
1474 event_owners.push_back(disp);
1475 }
1476 }
nisseede5da42017-01-12 05:15:36 -08001477 RTC_DCHECK(iterators_.back() == &i);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001478 iterators_.pop_back();
1479 }
1480
1481 // Which is shorter, the delay wait or the asked wait?
1482
Honghai Zhang82d78622016-05-06 11:29:15 -07001483 int64_t cmsNext;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001484 if (cmsWait == kForever) {
1485 cmsNext = cmsWait;
1486 } else {
Honghai Zhang82d78622016-05-06 11:29:15 -07001487 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001488 }
1489
1490 // Wait for one of the events to signal
1491 DWORD dw = WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()),
1492 &events[0],
1493 false,
Honghai Zhang82d78622016-05-06 11:29:15 -07001494 static_cast<DWORD>(cmsNext),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001495 false);
1496
1497 if (dw == WSA_WAIT_FAILED) {
1498 // Failed?
jbauch095ae152015-12-18 01:39:55 -08001499 // TODO(pthatcher): need a better strategy than this!
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001500 WSAGetLastError();
nissec80e7412017-01-11 05:56:46 -08001501 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001502 return false;
1503 } else if (dw == WSA_WAIT_TIMEOUT) {
1504 // Timeout?
1505 return true;
1506 } else {
1507 // Figure out which one it is and call it
1508 CritScope cr(&crit_);
1509 int index = dw - WSA_WAIT_EVENT_0;
1510 if (index > 0) {
1511 --index; // The first event is the socket event
1512 event_owners[index]->OnPreEvent(0);
1513 event_owners[index]->OnEvent(0, 0);
1514 } else if (process_io) {
1515 size_t i = 0, end = dispatchers_.size();
1516 iterators_.push_back(&i);
1517 iterators_.push_back(&end); // Don't iterate over new dispatchers.
1518 while (i < end) {
1519 Dispatcher* disp = dispatchers_[i++];
1520 SOCKET s = disp->GetSocket();
1521 if (s == INVALID_SOCKET)
1522 continue;
1523
1524 WSANETWORKEVENTS wsaEvents;
1525 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1526 if (err == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001527 {
1528 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1529 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
1530 LOG(WARNING) << "PhysicalSocketServer got FD_READ_BIT error "
1531 << wsaEvents.iErrorCode[FD_READ_BIT];
1532 }
1533 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1534 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
1535 LOG(WARNING) << "PhysicalSocketServer got FD_WRITE_BIT error "
1536 << wsaEvents.iErrorCode[FD_WRITE_BIT];
1537 }
1538 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1539 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
1540 LOG(WARNING) << "PhysicalSocketServer got FD_CONNECT_BIT error "
1541 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
1542 }
1543 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1544 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
1545 LOG(WARNING) << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1546 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
1547 }
1548 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1549 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
1550 LOG(WARNING) << "PhysicalSocketServer got FD_CLOSE_BIT error "
1551 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
1552 }
1553 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001554 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001555 int errcode = 0;
1556 if (wsaEvents.lNetworkEvents & FD_READ)
1557 ff |= DE_READ;
1558 if (wsaEvents.lNetworkEvents & FD_WRITE)
1559 ff |= DE_WRITE;
1560 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1561 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1562 ff |= DE_CONNECT;
1563 } else {
1564 ff |= DE_CLOSE;
1565 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1566 }
1567 }
1568 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1569 ff |= DE_ACCEPT;
1570 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1571 ff |= DE_CLOSE;
1572 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1573 }
1574 if (ff != 0) {
1575 disp->OnPreEvent(ff);
1576 disp->OnEvent(ff, errcode);
1577 }
1578 }
1579 }
nisseede5da42017-01-12 05:15:36 -08001580 RTC_DCHECK(iterators_.back() == &end);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001581 iterators_.pop_back();
nisseede5da42017-01-12 05:15:36 -08001582 RTC_DCHECK(iterators_.back() == &i);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001583 iterators_.pop_back();
1584 }
1585
1586 // Reset the network event until new activity occurs
1587 WSAResetEvent(socket_ev_);
1588 }
1589
1590 // Break?
1591 if (!fWait_)
1592 break;
1593 cmsElapsed = TimeSince(msStart);
1594 if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
1595 break;
1596 }
1597 }
1598
1599 // Done
1600 return true;
1601}
honghaizcec0a082016-01-15 14:49:09 -08001602#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001603
1604} // namespace rtc