blob: 5b49638bd658feeac2f770ff6a26c913c9f9a849 [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"
50#include "webrtc/base/winping.h"
51#include "webrtc/base/win32socketinit.h"
52
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000053#if defined(WEBRTC_POSIX)
54#include <netinet/tcp.h> // for TCP_NODELAY
55#define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h
56typedef void* SockOptArg;
Stefan Holmer9131efd2016-05-23 18:19:26 +020057
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000058#endif // WEBRTC_POSIX
59
Stefan Holmer3ebb3ef2016-05-23 20:26:11 +020060#if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) && !defined(__native_client__)
61
Stefan Holmer9131efd2016-05-23 18:19:26 +020062int64_t GetSocketRecvTimestamp(int socket) {
63 struct timeval tv_ioctl;
64 int ret = ioctl(socket, SIOCGSTAMP, &tv_ioctl);
65 if (ret != 0)
66 return -1;
67 int64_t timestamp =
68 rtc::kNumMicrosecsPerSec * static_cast<int64_t>(tv_ioctl.tv_sec) +
69 static_cast<int64_t>(tv_ioctl.tv_usec);
70 return timestamp;
71}
72
73#else
74
75int64_t GetSocketRecvTimestamp(int socket) {
76 return -1;
77}
78#endif
79
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000080#if defined(WEBRTC_WIN)
81typedef char* SockOptArg;
82#endif
83
84namespace rtc {
85
danilchapbebf54c2016-04-28 01:32:48 -070086std::unique_ptr<SocketServer> SocketServer::CreateDefault() {
87#if defined(__native_client__)
88 return std::unique_ptr<SocketServer>(new rtc::NullSocketServer);
89#else
90 return std::unique_ptr<SocketServer>(new rtc::PhysicalSocketServer);
91#endif
92}
93
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000094#if defined(WEBRTC_WIN)
95// Standard MTUs, from RFC 1191
Peter Boström0c4e06b2015-10-07 12:23:21 +020096const uint16_t PACKET_MAXIMUMS[] = {
97 65535, // Theoretical maximum, Hyperchannel
98 32000, // Nothing
99 17914, // 16Mb IBM Token Ring
100 8166, // IEEE 802.4
101 // 4464, // IEEE 802.5 (4Mb max)
102 4352, // FDDI
103 // 2048, // Wideband Network
104 2002, // IEEE 802.5 (4Mb recommended)
105 // 1536, // Expermental Ethernet Networks
106 // 1500, // Ethernet, Point-to-Point (default)
107 1492, // IEEE 802.3
108 1006, // SLIP, ARPANET
109 // 576, // X.25 Networks
110 // 544, // DEC IP Portal
111 // 512, // NETBIOS
112 508, // IEEE 802/Source-Rt Bridge, ARCNET
113 296, // Point-to-Point (low delay)
114 68, // Official minimum
115 0, // End of list marker
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000116};
117
118static const int IP_HEADER_SIZE = 20u;
119static const int IPV6_HEADER_SIZE = 40u;
120static const int ICMP_HEADER_SIZE = 8u;
121static const int ICMP_PING_TIMEOUT_MILLIS = 10000u;
122#endif
123
jbauch095ae152015-12-18 01:39:55 -0800124PhysicalSocket::PhysicalSocket(PhysicalSocketServer* ss, SOCKET s)
125 : ss_(ss), s_(s), enabled_events_(0), error_(0),
126 state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED),
127 resolver_(nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000128#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800129 // EnsureWinsockInit() ensures that winsock is initialized. The default
130 // version of this function doesn't do anything because winsock is
131 // initialized by constructor of a static object. If neccessary libjingle
132 // users can link it with a different version of this function by replacing
133 // win32socketinit.cc. See win32socketinit.cc for more details.
134 EnsureWinsockInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000135#endif
jbauch095ae152015-12-18 01:39:55 -0800136 if (s_ != INVALID_SOCKET) {
137 enabled_events_ = DE_READ | DE_WRITE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000138
jbauch095ae152015-12-18 01:39:55 -0800139 int type = SOCK_STREAM;
140 socklen_t len = sizeof(type);
nissec16fa5e2017-02-07 07:18:43 -0800141 const int res =
142 getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len);
143 RTC_DCHECK_EQ(0, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000144 udp_ = (SOCK_DGRAM == type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000145 }
jbauch095ae152015-12-18 01:39:55 -0800146}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000147
jbauch095ae152015-12-18 01:39:55 -0800148PhysicalSocket::~PhysicalSocket() {
149 Close();
150}
151
152bool PhysicalSocket::Create(int family, int type) {
153 Close();
154 s_ = ::socket(family, type, 0);
155 udp_ = (SOCK_DGRAM == type);
156 UpdateLastError();
157 if (udp_)
158 enabled_events_ = DE_READ | DE_WRITE;
159 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();
270 if (err == 0) {
271 state_ = CS_CONNECTED;
272 } else if (IsBlockingError(GetError())) {
273 state_ = CS_CONNECTING;
274 enabled_events_ |= DE_CONNECT;
275 } else {
276 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000277 }
278
jbauch095ae152015-12-18 01:39:55 -0800279 enabled_events_ |= DE_READ | DE_WRITE;
280 return 0;
281}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000282
jbauch095ae152015-12-18 01:39:55 -0800283int PhysicalSocket::GetError() const {
284 CritScope cs(&crit_);
285 return error_;
286}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000287
jbauch095ae152015-12-18 01:39:55 -0800288void PhysicalSocket::SetError(int error) {
289 CritScope cs(&crit_);
290 error_ = error;
291}
292
293AsyncSocket::ConnState PhysicalSocket::GetState() const {
294 return state_;
295}
296
297int PhysicalSocket::GetOption(Option opt, int* value) {
298 int slevel;
299 int sopt;
300 if (TranslateOption(opt, &slevel, &sopt) == -1)
301 return -1;
302 socklen_t optlen = sizeof(*value);
303 int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
304 if (ret != -1 && opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000305#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800306 *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000307#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000308 }
jbauch095ae152015-12-18 01:39:55 -0800309 return ret;
310}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000311
jbauch095ae152015-12-18 01:39:55 -0800312int PhysicalSocket::SetOption(Option opt, int value) {
313 int slevel;
314 int sopt;
315 if (TranslateOption(opt, &slevel, &sopt) == -1)
316 return -1;
317 if (opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000318#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800319 value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000320#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000321 }
jbauch095ae152015-12-18 01:39:55 -0800322 return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
323}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000324
jbauch095ae152015-12-18 01:39:55 -0800325int PhysicalSocket::Send(const void* pv, size_t cb) {
jbauchf2a2bf42016-02-03 16:45:32 -0800326 int sent = DoSend(s_, reinterpret_cast<const char *>(pv),
327 static_cast<int>(cb),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000328#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800329 // Suppress SIGPIPE. Without this, attempting to send on a socket whose
330 // other end is closed will result in a SIGPIPE signal being raised to
331 // our process, which by default will terminate the process, which we
332 // don't want. By specifying this flag, we'll just get the error EPIPE
333 // instead and can handle the error gracefully.
334 MSG_NOSIGNAL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000335#else
jbauch095ae152015-12-18 01:39:55 -0800336 0
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000337#endif
jbauch095ae152015-12-18 01:39:55 -0800338 );
339 UpdateLastError();
340 MaybeRemapSendError();
341 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800342 RTC_DCHECK(sent <= static_cast<int>(cb));
jbauchf2a2bf42016-02-03 16:45:32 -0800343 if ((sent > 0 && sent < static_cast<int>(cb)) ||
344 (sent < 0 && IsBlockingError(GetError()))) {
jbauch095ae152015-12-18 01:39:55 -0800345 enabled_events_ |= DE_WRITE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000346 }
jbauch095ae152015-12-18 01:39:55 -0800347 return sent;
348}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000349
jbauch095ae152015-12-18 01:39:55 -0800350int PhysicalSocket::SendTo(const void* buffer,
351 size_t length,
352 const SocketAddress& addr) {
353 sockaddr_storage saddr;
354 size_t len = addr.ToSockAddrStorage(&saddr);
jbauchf2a2bf42016-02-03 16:45:32 -0800355 int sent = DoSendTo(
jbauch095ae152015-12-18 01:39:55 -0800356 s_, static_cast<const char *>(buffer), static_cast<int>(length),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000357#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800358 // Suppress SIGPIPE. See above for explanation.
359 MSG_NOSIGNAL,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000360#else
jbauch095ae152015-12-18 01:39:55 -0800361 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000362#endif
jbauch095ae152015-12-18 01:39:55 -0800363 reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
364 UpdateLastError();
365 MaybeRemapSendError();
366 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800367 RTC_DCHECK(sent <= static_cast<int>(length));
jbauchf2a2bf42016-02-03 16:45:32 -0800368 if ((sent > 0 && sent < static_cast<int>(length)) ||
369 (sent < 0 && IsBlockingError(GetError()))) {
jbauch095ae152015-12-18 01:39:55 -0800370 enabled_events_ |= DE_WRITE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000371 }
jbauch095ae152015-12-18 01:39:55 -0800372 return sent;
373}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000374
Stefan Holmer9131efd2016-05-23 18:19:26 +0200375int PhysicalSocket::Recv(void* buffer, size_t length, int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800376 int received = ::recv(s_, static_cast<char*>(buffer),
377 static_cast<int>(length), 0);
378 if ((received == 0) && (length != 0)) {
379 // Note: on graceful shutdown, recv can return 0. In this case, we
380 // pretend it is blocking, and then signal close, so that simplifying
381 // assumptions can be made about Recv.
382 LOG(LS_WARNING) << "EOF from socket; deferring close event";
383 // Must turn this back on so that the select() loop will notice the close
384 // event.
385 enabled_events_ |= DE_READ;
386 SetError(EWOULDBLOCK);
387 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000388 }
Stefan Holmer9131efd2016-05-23 18:19:26 +0200389 if (timestamp) {
390 *timestamp = GetSocketRecvTimestamp(s_);
391 }
jbauch095ae152015-12-18 01:39:55 -0800392 UpdateLastError();
393 int error = GetError();
394 bool success = (received >= 0) || IsBlockingError(error);
395 if (udp_ || success) {
396 enabled_events_ |= DE_READ;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000397 }
jbauch095ae152015-12-18 01:39:55 -0800398 if (!success) {
399 LOG_F(LS_VERBOSE) << "Error = " << error;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000400 }
jbauch095ae152015-12-18 01:39:55 -0800401 return received;
402}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000403
jbauch095ae152015-12-18 01:39:55 -0800404int PhysicalSocket::RecvFrom(void* buffer,
405 size_t length,
Stefan Holmer9131efd2016-05-23 18:19:26 +0200406 SocketAddress* out_addr,
407 int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800408 sockaddr_storage addr_storage;
409 socklen_t addr_len = sizeof(addr_storage);
410 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
411 int received = ::recvfrom(s_, static_cast<char*>(buffer),
412 static_cast<int>(length), 0, addr, &addr_len);
Stefan Holmer9131efd2016-05-23 18:19:26 +0200413 if (timestamp) {
414 *timestamp = GetSocketRecvTimestamp(s_);
415 }
jbauch095ae152015-12-18 01:39:55 -0800416 UpdateLastError();
417 if ((received >= 0) && (out_addr != nullptr))
418 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
419 int error = GetError();
420 bool success = (received >= 0) || IsBlockingError(error);
421 if (udp_ || success) {
422 enabled_events_ |= DE_READ;
423 }
424 if (!success) {
425 LOG_F(LS_VERBOSE) << "Error = " << error;
426 }
427 return received;
428}
429
430int PhysicalSocket::Listen(int backlog) {
431 int err = ::listen(s_, backlog);
432 UpdateLastError();
433 if (err == 0) {
434 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000435 enabled_events_ |= DE_ACCEPT;
jbauch095ae152015-12-18 01:39:55 -0800436#if !defined(NDEBUG)
437 dbg_addr_ = "Listening @ ";
438 dbg_addr_.append(GetLocalAddress().ToString());
439#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000440 }
jbauch095ae152015-12-18 01:39:55 -0800441 return err;
442}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000443
jbauch095ae152015-12-18 01:39:55 -0800444AsyncSocket* PhysicalSocket::Accept(SocketAddress* out_addr) {
445 // Always re-subscribe DE_ACCEPT to make sure new incoming connections will
446 // trigger an event even if DoAccept returns an error here.
447 enabled_events_ |= DE_ACCEPT;
448 sockaddr_storage addr_storage;
449 socklen_t addr_len = sizeof(addr_storage);
450 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
451 SOCKET s = DoAccept(s_, addr, &addr_len);
452 UpdateLastError();
453 if (s == INVALID_SOCKET)
454 return nullptr;
455 if (out_addr != nullptr)
456 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
457 return ss_->WrapSocket(s);
458}
459
460int PhysicalSocket::Close() {
461 if (s_ == INVALID_SOCKET)
462 return 0;
463 int err = ::closesocket(s_);
464 UpdateLastError();
465 s_ = INVALID_SOCKET;
466 state_ = CS_CLOSED;
467 enabled_events_ = 0;
468 if (resolver_) {
469 resolver_->Destroy(false);
470 resolver_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000471 }
jbauch095ae152015-12-18 01:39:55 -0800472 return err;
473}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000474
jbauch095ae152015-12-18 01:39:55 -0800475int PhysicalSocket::EstimateMTU(uint16_t* mtu) {
476 SocketAddress addr = GetRemoteAddress();
477 if (addr.IsAnyIP()) {
478 SetError(ENOTCONN);
479 return -1;
480 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000481
482#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800483 // Gets the interface MTU (TTL=1) for the interface used to reach |addr|.
484 WinPing ping;
485 if (!ping.IsValid()) {
486 SetError(EINVAL); // can't think of a better error ID
487 return -1;
488 }
489 int header_size = ICMP_HEADER_SIZE;
490 if (addr.family() == AF_INET6) {
491 header_size += IPV6_HEADER_SIZE;
492 } else if (addr.family() == AF_INET) {
493 header_size += IP_HEADER_SIZE;
494 }
495
496 for (int level = 0; PACKET_MAXIMUMS[level + 1] > 0; ++level) {
497 int32_t size = PACKET_MAXIMUMS[level] - header_size;
498 WinPing::PingResult result = ping.Ping(addr.ipaddr(), size,
499 ICMP_PING_TIMEOUT_MILLIS,
500 1, false);
501 if (result == WinPing::PING_FAIL) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000502 SetError(EINVAL); // can't think of a better error ID
503 return -1;
jbauch095ae152015-12-18 01:39:55 -0800504 } else if (result != WinPing::PING_TOO_LARGE) {
505 *mtu = PACKET_MAXIMUMS[level];
506 return 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000507 }
jbauch095ae152015-12-18 01:39:55 -0800508 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000509
nissec80e7412017-01-11 05:56:46 -0800510 RTC_NOTREACHED();
jbauch095ae152015-12-18 01:39:55 -0800511 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000512#elif defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800513 // No simple way to do this on Mac OS X.
514 // SIOCGIFMTU would work if we knew which interface would be used, but
515 // figuring that out is pretty complicated. For now we'll return an error
516 // and let the caller pick a default MTU.
517 SetError(EINVAL);
518 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000519#elif defined(WEBRTC_LINUX)
jbauch095ae152015-12-18 01:39:55 -0800520 // Gets the path MTU.
521 int value;
522 socklen_t vlen = sizeof(value);
523 int err = getsockopt(s_, IPPROTO_IP, IP_MTU, &value, &vlen);
524 if (err < 0) {
525 UpdateLastError();
526 return err;
527 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000528
nisseede5da42017-01-12 05:15:36 -0800529 RTC_DCHECK((0 <= value) && (value <= 65536));
jbauch095ae152015-12-18 01:39:55 -0800530 *mtu = value;
531 return 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000532#elif defined(__native_client__)
jbauch095ae152015-12-18 01:39:55 -0800533 // Most socket operations, including this, will fail in NaCl's sandbox.
534 error_ = EACCES;
535 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000536#endif
jbauch095ae152015-12-18 01:39:55 -0800537}
538
jbauch095ae152015-12-18 01:39:55 -0800539SOCKET PhysicalSocket::DoAccept(SOCKET socket,
540 sockaddr* addr,
541 socklen_t* addrlen) {
542 return ::accept(socket, addr, addrlen);
543}
544
jbauchf2a2bf42016-02-03 16:45:32 -0800545int PhysicalSocket::DoSend(SOCKET socket, const char* buf, int len, int flags) {
546 return ::send(socket, buf, len, flags);
547}
548
549int PhysicalSocket::DoSendTo(SOCKET socket,
550 const char* buf,
551 int len,
552 int flags,
553 const struct sockaddr* dest_addr,
554 socklen_t addrlen) {
555 return ::sendto(socket, buf, len, flags, dest_addr, addrlen);
556}
557
jbauch095ae152015-12-18 01:39:55 -0800558void PhysicalSocket::OnResolveResult(AsyncResolverInterface* resolver) {
559 if (resolver != resolver_) {
560 return;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000561 }
562
jbauch095ae152015-12-18 01:39:55 -0800563 int error = resolver_->GetError();
564 if (error == 0) {
565 error = DoConnect(resolver_->address());
566 } else {
567 Close();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000568 }
569
jbauch095ae152015-12-18 01:39:55 -0800570 if (error) {
571 SetError(error);
572 SignalCloseEvent(this, error);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000573 }
jbauch095ae152015-12-18 01:39:55 -0800574}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000575
jbauch095ae152015-12-18 01:39:55 -0800576void PhysicalSocket::UpdateLastError() {
577 SetError(LAST_SYSTEM_ERROR);
578}
579
580void PhysicalSocket::MaybeRemapSendError() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000581#if defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800582 // https://developer.apple.com/library/mac/documentation/Darwin/
583 // Reference/ManPages/man2/sendto.2.html
584 // ENOBUFS - The output queue for a network interface is full.
585 // This generally indicates that the interface has stopped sending,
586 // but may be caused by transient congestion.
587 if (GetError() == ENOBUFS) {
588 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000589 }
jbauch095ae152015-12-18 01:39:55 -0800590#endif
591}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000592
jbauch095ae152015-12-18 01:39:55 -0800593int PhysicalSocket::TranslateOption(Option opt, int* slevel, int* sopt) {
594 switch (opt) {
595 case OPT_DONTFRAGMENT:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000596#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800597 *slevel = IPPROTO_IP;
598 *sopt = IP_DONTFRAGMENT;
599 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000600#elif defined(WEBRTC_MAC) || defined(BSD) || defined(__native_client__)
jbauch095ae152015-12-18 01:39:55 -0800601 LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
602 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000603#elif defined(WEBRTC_POSIX)
jbauch095ae152015-12-18 01:39:55 -0800604 *slevel = IPPROTO_IP;
605 *sopt = IP_MTU_DISCOVER;
606 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000607#endif
jbauch095ae152015-12-18 01:39:55 -0800608 case OPT_RCVBUF:
609 *slevel = SOL_SOCKET;
610 *sopt = SO_RCVBUF;
611 break;
612 case OPT_SNDBUF:
613 *slevel = SOL_SOCKET;
614 *sopt = SO_SNDBUF;
615 break;
616 case OPT_NODELAY:
617 *slevel = IPPROTO_TCP;
618 *sopt = TCP_NODELAY;
619 break;
620 case OPT_DSCP:
621 LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
622 return -1;
623 case OPT_RTP_SENDTIME_EXTN_ID:
624 return -1; // No logging is necessary as this not a OS socket option.
625 default:
nissec80e7412017-01-11 05:56:46 -0800626 RTC_NOTREACHED();
jbauch095ae152015-12-18 01:39:55 -0800627 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000628 }
jbauch095ae152015-12-18 01:39:55 -0800629 return 0;
630}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000631
jbauch4331fcd2016-01-06 22:20:28 -0800632SocketDispatcher::SocketDispatcher(PhysicalSocketServer *ss)
633#if defined(WEBRTC_WIN)
634 : PhysicalSocket(ss), id_(0), signal_close_(false)
635#else
636 : PhysicalSocket(ss)
637#endif
638{
639}
640
641SocketDispatcher::SocketDispatcher(SOCKET s, PhysicalSocketServer *ss)
642#if defined(WEBRTC_WIN)
643 : PhysicalSocket(ss, s), id_(0), signal_close_(false)
644#else
645 : PhysicalSocket(ss, s)
646#endif
647{
648}
649
650SocketDispatcher::~SocketDispatcher() {
651 Close();
652}
653
654bool SocketDispatcher::Initialize() {
nisseede5da42017-01-12 05:15:36 -0800655 RTC_DCHECK(s_ != INVALID_SOCKET);
jbauch4331fcd2016-01-06 22:20:28 -0800656 // Must be a non-blocking
657#if defined(WEBRTC_WIN)
658 u_long argp = 1;
659 ioctlsocket(s_, FIONBIO, &argp);
660#elif defined(WEBRTC_POSIX)
661 fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
662#endif
663 ss_->Add(this);
664 return true;
665}
666
667bool SocketDispatcher::Create(int type) {
668 return Create(AF_INET, type);
669}
670
671bool SocketDispatcher::Create(int family, int type) {
672 // Change the socket to be non-blocking.
673 if (!PhysicalSocket::Create(family, type))
674 return false;
675
676 if (!Initialize())
677 return false;
678
679#if defined(WEBRTC_WIN)
680 do { id_ = ++next_id_; } while (id_ == 0);
681#endif
682 return true;
683}
684
685#if defined(WEBRTC_WIN)
686
687WSAEVENT SocketDispatcher::GetWSAEvent() {
688 return WSA_INVALID_EVENT;
689}
690
691SOCKET SocketDispatcher::GetSocket() {
692 return s_;
693}
694
695bool SocketDispatcher::CheckSignalClose() {
696 if (!signal_close_)
697 return false;
698
699 char ch;
700 if (recv(s_, &ch, 1, MSG_PEEK) > 0)
701 return false;
702
703 state_ = CS_CLOSED;
704 signal_close_ = false;
705 SignalCloseEvent(this, signal_err_);
706 return true;
707}
708
709int SocketDispatcher::next_id_ = 0;
710
711#elif defined(WEBRTC_POSIX)
712
713int SocketDispatcher::GetDescriptor() {
714 return s_;
715}
716
717bool SocketDispatcher::IsDescriptorClosed() {
deadbeeffaedf7f2017-02-09 15:09:22 -0800718 if (udp_) {
719 // The MSG_PEEK trick doesn't work for UDP, since (at least in some
720 // circumstances) it requires reading an entire UDP packet, which would be
721 // bad for performance here. So, just check whether |s_| has been closed,
722 // which should be sufficient.
723 return s_ == INVALID_SOCKET;
724 }
jbauch4331fcd2016-01-06 22:20:28 -0800725 // We don't have a reliable way of distinguishing end-of-stream
726 // from readability. So test on each readable call. Is this
727 // inefficient? Probably.
728 char ch;
729 ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
730 if (res > 0) {
731 // Data available, so not closed.
732 return false;
733 } else if (res == 0) {
734 // EOF, so closed.
735 return true;
736 } else { // error
737 switch (errno) {
738 // Returned if we've already closed s_.
739 case EBADF:
740 // Returned during ungraceful peer shutdown.
741 case ECONNRESET:
742 return true;
deadbeeffaedf7f2017-02-09 15:09:22 -0800743 // The normal blocking error; don't log anything.
744 case EWOULDBLOCK:
745 // Interrupted system call.
746 case EINTR:
747 return false;
jbauch4331fcd2016-01-06 22:20:28 -0800748 default:
749 // Assume that all other errors are just blocking errors, meaning the
750 // connection is still good but we just can't read from it right now.
751 // This should only happen when connecting (and at most once), because
752 // in all other cases this function is only called if the file
753 // descriptor is already known to be in the readable state. However,
754 // it's not necessary a problem if we spuriously interpret a
755 // "connection lost"-type error as a blocking error, because typically
756 // the next recv() will get EOF, so we'll still eventually notice that
757 // the socket is closed.
758 LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
759 return false;
760 }
761 }
762}
763
764#endif // WEBRTC_POSIX
765
766uint32_t SocketDispatcher::GetRequestedEvents() {
767 return enabled_events_;
768}
769
770void SocketDispatcher::OnPreEvent(uint32_t ff) {
771 if ((ff & DE_CONNECT) != 0)
772 state_ = CS_CONNECTED;
773
774#if defined(WEBRTC_WIN)
775 // We set CS_CLOSED from CheckSignalClose.
776#elif defined(WEBRTC_POSIX)
777 if ((ff & DE_CLOSE) != 0)
778 state_ = CS_CLOSED;
779#endif
780}
781
782#if defined(WEBRTC_WIN)
783
784void SocketDispatcher::OnEvent(uint32_t ff, int err) {
785 int cache_id = id_;
786 // Make sure we deliver connect/accept first. Otherwise, consumers may see
787 // something like a READ followed by a CONNECT, which would be odd.
788 if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
789 if (ff != DE_CONNECT)
790 LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
791 enabled_events_ &= ~DE_CONNECT;
792#if !defined(NDEBUG)
793 dbg_addr_ = "Connected @ ";
794 dbg_addr_.append(GetRemoteAddress().ToString());
795#endif
796 SignalConnectEvent(this);
797 }
798 if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
799 enabled_events_ &= ~DE_ACCEPT;
800 SignalReadEvent(this);
801 }
802 if ((ff & DE_READ) != 0) {
803 enabled_events_ &= ~DE_READ;
804 SignalReadEvent(this);
805 }
806 if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
807 enabled_events_ &= ~DE_WRITE;
808 SignalWriteEvent(this);
809 }
810 if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
811 signal_close_ = true;
812 signal_err_ = err;
813 }
814}
815
816#elif defined(WEBRTC_POSIX)
817
818void SocketDispatcher::OnEvent(uint32_t ff, int err) {
819 // Make sure we deliver connect/accept first. Otherwise, consumers may see
820 // something like a READ followed by a CONNECT, which would be odd.
821 if ((ff & DE_CONNECT) != 0) {
822 enabled_events_ &= ~DE_CONNECT;
823 SignalConnectEvent(this);
824 }
825 if ((ff & DE_ACCEPT) != 0) {
826 enabled_events_ &= ~DE_ACCEPT;
827 SignalReadEvent(this);
828 }
829 if ((ff & DE_READ) != 0) {
830 enabled_events_ &= ~DE_READ;
831 SignalReadEvent(this);
832 }
833 if ((ff & DE_WRITE) != 0) {
834 enabled_events_ &= ~DE_WRITE;
835 SignalWriteEvent(this);
836 }
837 if ((ff & DE_CLOSE) != 0) {
838 // The socket is now dead to us, so stop checking it.
839 enabled_events_ = 0;
840 SignalCloseEvent(this, err);
841 }
842}
843
844#endif // WEBRTC_POSIX
845
846int SocketDispatcher::Close() {
847 if (s_ == INVALID_SOCKET)
848 return 0;
849
850#if defined(WEBRTC_WIN)
851 id_ = 0;
852 signal_close_ = false;
853#endif
854 ss_->Remove(this);
855 return PhysicalSocket::Close();
856}
857
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000858#if defined(WEBRTC_POSIX)
859class EventDispatcher : public Dispatcher {
860 public:
861 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
862 if (pipe(afd_) < 0)
863 LOG(LERROR) << "pipe failed";
864 ss_->Add(this);
865 }
866
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000867 ~EventDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000868 ss_->Remove(this);
869 close(afd_[0]);
870 close(afd_[1]);
871 }
872
873 virtual void Signal() {
874 CritScope cs(&crit_);
875 if (!fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200876 const uint8_t b[1] = {0};
nissec16fa5e2017-02-07 07:18:43 -0800877 const ssize_t res = write(afd_[1], b, sizeof(b));
878 RTC_DCHECK_EQ(1, res);
879 fSignaled_ = true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000880 }
881 }
882
Peter Boström0c4e06b2015-10-07 12:23:21 +0200883 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000884
Peter Boström0c4e06b2015-10-07 12:23:21 +0200885 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000886 // It is not possible to perfectly emulate an auto-resetting event with
887 // pipes. This simulates it by resetting before the event is handled.
888
889 CritScope cs(&crit_);
890 if (fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200891 uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
nissec16fa5e2017-02-07 07:18:43 -0800892 const ssize_t res = read(afd_[0], b, sizeof(b));
893 RTC_DCHECK_EQ(1, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000894 fSignaled_ = false;
895 }
896 }
897
nissec80e7412017-01-11 05:56:46 -0800898 void OnEvent(uint32_t ff, int err) override { RTC_NOTREACHED(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000899
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000900 int GetDescriptor() override { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000901
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000902 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000903
904 private:
905 PhysicalSocketServer *ss_;
906 int afd_[2];
907 bool fSignaled_;
908 CriticalSection crit_;
909};
910
911// These two classes use the self-pipe trick to deliver POSIX signals to our
912// select loop. This is the only safe, reliable, cross-platform way to do
913// non-trivial things with a POSIX signal in an event-driven program (until
914// proper pselect() implementations become ubiquitous).
915
916class PosixSignalHandler {
917 public:
918 // POSIX only specifies 32 signals, but in principle the system might have
919 // more and the programmer might choose to use them, so we size our array
920 // for 128.
921 static const int kNumPosixSignals = 128;
922
923 // There is just a single global instance. (Signal handlers do not get any
924 // sort of user-defined void * parameter, so they can't access anything that
925 // isn't global.)
926 static PosixSignalHandler* Instance() {
Andrew MacDonald469c2c02015-05-22 17:50:26 -0700927 RTC_DEFINE_STATIC_LOCAL(PosixSignalHandler, instance, ());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000928 return &instance;
929 }
930
931 // Returns true if the given signal number is set.
932 bool IsSignalSet(int signum) const {
nisseede5da42017-01-12 05:15:36 -0800933 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800934 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000935 return received_signal_[signum];
936 } else {
937 return false;
938 }
939 }
940
941 // Clears the given signal number.
942 void ClearSignal(int signum) {
nisseede5da42017-01-12 05:15:36 -0800943 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800944 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000945 received_signal_[signum] = false;
946 }
947 }
948
949 // Returns the file descriptor to monitor for signal events.
950 int GetDescriptor() const {
951 return afd_[0];
952 }
953
954 // This is called directly from our real signal handler, so it must be
955 // signal-handler-safe. That means it cannot assume anything about the
956 // user-level state of the process, since the handler could be executed at any
957 // time on any thread.
958 void OnPosixSignalReceived(int signum) {
tfarina5237aaf2015-11-10 23:44:30 -0800959 if (signum >= static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000960 // We don't have space in our array for this.
961 return;
962 }
963 // Set a flag saying we've seen this signal.
964 received_signal_[signum] = true;
965 // Notify application code that we got a signal.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200966 const uint8_t b[1] = {0};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000967 if (-1 == write(afd_[1], b, sizeof(b))) {
968 // Nothing we can do here. If there's an error somehow then there's
969 // nothing we can safely do from a signal handler.
970 // No, we can't even safely log it.
971 // But, we still have to check the return value here. Otherwise,
972 // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
973 return;
974 }
975 }
976
977 private:
978 PosixSignalHandler() {
979 if (pipe(afd_) < 0) {
980 LOG_ERR(LS_ERROR) << "pipe failed";
981 return;
982 }
983 if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
984 LOG_ERR(LS_WARNING) << "fcntl #1 failed";
985 }
986 if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
987 LOG_ERR(LS_WARNING) << "fcntl #2 failed";
988 }
989 memset(const_cast<void *>(static_cast<volatile void *>(received_signal_)),
990 0,
991 sizeof(received_signal_));
992 }
993
994 ~PosixSignalHandler() {
995 int fd1 = afd_[0];
996 int fd2 = afd_[1];
997 // We clobber the stored file descriptor numbers here or else in principle
998 // a signal that happens to be delivered during application termination
999 // could erroneously write a zero byte to an unrelated file handle in
1000 // OnPosixSignalReceived() if some other file happens to be opened later
1001 // during shutdown and happens to be given the same file descriptor number
1002 // as our pipe had. Unfortunately even with this precaution there is still a
1003 // race where that could occur if said signal happens to be handled
1004 // concurrently with this code and happens to have already read the value of
1005 // afd_[1] from memory before we clobber it, but that's unlikely.
1006 afd_[0] = -1;
1007 afd_[1] = -1;
1008 close(fd1);
1009 close(fd2);
1010 }
1011
1012 int afd_[2];
1013 // These are boolean flags that will be set in our signal handler and read
1014 // and cleared from Wait(). There is a race involved in this, but it is
1015 // benign. The signal handler sets the flag before signaling the pipe, so
1016 // we'll never end up blocking in select() while a flag is still true.
1017 // However, if two of the same signal arrive close to each other then it's
1018 // possible that the second time the handler may set the flag while it's still
1019 // true, meaning that signal will be missed. But the first occurrence of it
1020 // will still be handled, so this isn't a problem.
1021 // Volatile is not necessary here for correctness, but this data _is_ volatile
1022 // so I've marked it as such.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001023 volatile uint8_t received_signal_[kNumPosixSignals];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001024};
1025
1026class PosixSignalDispatcher : public Dispatcher {
1027 public:
1028 PosixSignalDispatcher(PhysicalSocketServer *owner) : owner_(owner) {
1029 owner_->Add(this);
1030 }
1031
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001032 ~PosixSignalDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001033 owner_->Remove(this);
1034 }
1035
Peter Boström0c4e06b2015-10-07 12:23:21 +02001036 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001037
Peter Boström0c4e06b2015-10-07 12:23:21 +02001038 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001039 // Events might get grouped if signals come very fast, so we read out up to
1040 // 16 bytes to make sure we keep the pipe empty.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001041 uint8_t b[16];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001042 ssize_t ret = read(GetDescriptor(), b, sizeof(b));
1043 if (ret < 0) {
1044 LOG_ERR(LS_WARNING) << "Error in read()";
1045 } else if (ret == 0) {
1046 LOG(LS_WARNING) << "Should have read at least one byte";
1047 }
1048 }
1049
Peter Boström0c4e06b2015-10-07 12:23:21 +02001050 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001051 for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
1052 ++signum) {
1053 if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
1054 PosixSignalHandler::Instance()->ClearSignal(signum);
1055 HandlerMap::iterator i = handlers_.find(signum);
1056 if (i == handlers_.end()) {
1057 // This can happen if a signal is delivered to our process at around
1058 // the same time as we unset our handler for it. It is not an error
1059 // condition, but it's unusual enough to be worth logging.
1060 LOG(LS_INFO) << "Received signal with no handler: " << signum;
1061 } else {
1062 // Otherwise, execute our handler.
1063 (*i->second)(signum);
1064 }
1065 }
1066 }
1067 }
1068
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001069 int GetDescriptor() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001070 return PosixSignalHandler::Instance()->GetDescriptor();
1071 }
1072
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001073 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001074
1075 void SetHandler(int signum, void (*handler)(int)) {
1076 handlers_[signum] = handler;
1077 }
1078
1079 void ClearHandler(int signum) {
1080 handlers_.erase(signum);
1081 }
1082
1083 bool HasHandlers() {
1084 return !handlers_.empty();
1085 }
1086
1087 private:
1088 typedef std::map<int, void (*)(int)> HandlerMap;
1089
1090 HandlerMap handlers_;
1091 // Our owner.
1092 PhysicalSocketServer *owner_;
1093};
1094
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001095#endif // WEBRTC_POSIX
1096
1097#if defined(WEBRTC_WIN)
Peter Boström0c4e06b2015-10-07 12:23:21 +02001098static uint32_t FlagsToEvents(uint32_t events) {
1099 uint32_t ffFD = FD_CLOSE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001100 if (events & DE_READ)
1101 ffFD |= FD_READ;
1102 if (events & DE_WRITE)
1103 ffFD |= FD_WRITE;
1104 if (events & DE_CONNECT)
1105 ffFD |= FD_CONNECT;
1106 if (events & DE_ACCEPT)
1107 ffFD |= FD_ACCEPT;
1108 return ffFD;
1109}
1110
1111class EventDispatcher : public Dispatcher {
1112 public:
1113 EventDispatcher(PhysicalSocketServer *ss) : ss_(ss) {
1114 hev_ = WSACreateEvent();
1115 if (hev_) {
1116 ss_->Add(this);
1117 }
1118 }
1119
1120 ~EventDispatcher() {
1121 if (hev_ != NULL) {
1122 ss_->Remove(this);
1123 WSACloseEvent(hev_);
1124 hev_ = NULL;
1125 }
1126 }
1127
1128 virtual void Signal() {
1129 if (hev_ != NULL)
1130 WSASetEvent(hev_);
1131 }
1132
Peter Boström0c4e06b2015-10-07 12:23:21 +02001133 virtual uint32_t GetRequestedEvents() { return 0; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001134
Peter Boström0c4e06b2015-10-07 12:23:21 +02001135 virtual void OnPreEvent(uint32_t ff) { WSAResetEvent(hev_); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001136
Peter Boström0c4e06b2015-10-07 12:23:21 +02001137 virtual void OnEvent(uint32_t ff, int err) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001138
1139 virtual WSAEVENT GetWSAEvent() {
1140 return hev_;
1141 }
1142
1143 virtual SOCKET GetSocket() {
1144 return INVALID_SOCKET;
1145 }
1146
1147 virtual bool CheckSignalClose() { return false; }
1148
1149private:
1150 PhysicalSocketServer* ss_;
1151 WSAEVENT hev_;
1152};
honghaizcec0a082016-01-15 14:49:09 -08001153#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001154
1155// Sets the value of a boolean value to false when signaled.
1156class Signaler : public EventDispatcher {
1157 public:
1158 Signaler(PhysicalSocketServer* ss, bool* pf)
1159 : EventDispatcher(ss), pf_(pf) {
1160 }
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001161 ~Signaler() override { }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001162
Peter Boström0c4e06b2015-10-07 12:23:21 +02001163 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001164 if (pf_)
1165 *pf_ = false;
1166 }
1167
1168 private:
1169 bool *pf_;
1170};
1171
1172PhysicalSocketServer::PhysicalSocketServer()
1173 : fWait_(false) {
1174 signal_wakeup_ = new Signaler(this, &fWait_);
1175#if defined(WEBRTC_WIN)
1176 socket_ev_ = WSACreateEvent();
1177#endif
1178}
1179
1180PhysicalSocketServer::~PhysicalSocketServer() {
1181#if defined(WEBRTC_WIN)
1182 WSACloseEvent(socket_ev_);
1183#endif
1184#if defined(WEBRTC_POSIX)
1185 signal_dispatcher_.reset();
1186#endif
1187 delete signal_wakeup_;
nisseede5da42017-01-12 05:15:36 -08001188 RTC_DCHECK(dispatchers_.empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001189}
1190
1191void PhysicalSocketServer::WakeUp() {
1192 signal_wakeup_->Signal();
1193}
1194
1195Socket* PhysicalSocketServer::CreateSocket(int type) {
1196 return CreateSocket(AF_INET, type);
1197}
1198
1199Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
1200 PhysicalSocket* socket = new PhysicalSocket(this);
1201 if (socket->Create(family, type)) {
1202 return socket;
1203 } else {
1204 delete socket;
jbauch095ae152015-12-18 01:39:55 -08001205 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001206 }
1207}
1208
1209AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int type) {
1210 return CreateAsyncSocket(AF_INET, type);
1211}
1212
1213AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
1214 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1215 if (dispatcher->Create(family, type)) {
1216 return dispatcher;
1217 } else {
1218 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001219 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001220 }
1221}
1222
1223AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
1224 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1225 if (dispatcher->Initialize()) {
1226 return dispatcher;
1227 } else {
1228 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001229 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001230 }
1231}
1232
1233void PhysicalSocketServer::Add(Dispatcher *pdispatcher) {
1234 CritScope cs(&crit_);
1235 // Prevent duplicates. This can cause dead dispatchers to stick around.
1236 DispatcherList::iterator pos = std::find(dispatchers_.begin(),
1237 dispatchers_.end(),
1238 pdispatcher);
1239 if (pos != dispatchers_.end())
1240 return;
1241 dispatchers_.push_back(pdispatcher);
1242}
1243
1244void PhysicalSocketServer::Remove(Dispatcher *pdispatcher) {
1245 CritScope cs(&crit_);
1246 DispatcherList::iterator pos = std::find(dispatchers_.begin(),
1247 dispatchers_.end(),
1248 pdispatcher);
1249 // We silently ignore duplicate calls to Add, so we should silently ignore
1250 // the (expected) symmetric calls to Remove. Note that this may still hide
1251 // a real issue, so we at least log a warning about it.
1252 if (pos == dispatchers_.end()) {
1253 LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
1254 << "dispatcher, potentially from a duplicate call to Add.";
1255 return;
1256 }
1257 size_t index = pos - dispatchers_.begin();
1258 dispatchers_.erase(pos);
1259 for (IteratorList::iterator it = iterators_.begin(); it != iterators_.end();
1260 ++it) {
1261 if (index < **it) {
1262 --**it;
1263 }
1264 }
1265}
1266
1267#if defined(WEBRTC_POSIX)
1268bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
1269 // Calculate timing information
1270
1271 struct timeval *ptvWait = NULL;
1272 struct timeval tvWait;
1273 struct timeval tvStop;
1274 if (cmsWait != kForever) {
1275 // Calculate wait timeval
1276 tvWait.tv_sec = cmsWait / 1000;
1277 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1278 ptvWait = &tvWait;
1279
1280 // Calculate when to return in a timeval
1281 gettimeofday(&tvStop, NULL);
1282 tvStop.tv_sec += tvWait.tv_sec;
1283 tvStop.tv_usec += tvWait.tv_usec;
1284 if (tvStop.tv_usec >= 1000000) {
1285 tvStop.tv_usec -= 1000000;
1286 tvStop.tv_sec += 1;
1287 }
1288 }
1289
1290 // Zero all fd_sets. Don't need to do this inside the loop since
1291 // select() zeros the descriptors not signaled
1292
1293 fd_set fdsRead;
1294 FD_ZERO(&fdsRead);
1295 fd_set fdsWrite;
1296 FD_ZERO(&fdsWrite);
pbos@webrtc.org27e58982014-10-07 17:56:53 +00001297 // Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1298 // inline assembly in FD_ZERO.
1299 // http://crbug.com/344505
1300#ifdef MEMORY_SANITIZER
1301 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1302 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1303#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001304
1305 fWait_ = true;
1306
1307 while (fWait_) {
1308 int fdmax = -1;
1309 {
1310 CritScope cr(&crit_);
1311 for (size_t i = 0; i < dispatchers_.size(); ++i) {
1312 // Query dispatchers for read and write wait state
1313 Dispatcher *pdispatcher = dispatchers_[i];
nisseede5da42017-01-12 05:15:36 -08001314 RTC_DCHECK(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001315 if (!process_io && (pdispatcher != signal_wakeup_))
1316 continue;
1317 int fd = pdispatcher->GetDescriptor();
1318 if (fd > fdmax)
1319 fdmax = fd;
1320
Peter Boström0c4e06b2015-10-07 12:23:21 +02001321 uint32_t ff = pdispatcher->GetRequestedEvents();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001322 if (ff & (DE_READ | DE_ACCEPT))
1323 FD_SET(fd, &fdsRead);
1324 if (ff & (DE_WRITE | DE_CONNECT))
1325 FD_SET(fd, &fdsWrite);
1326 }
1327 }
1328
1329 // Wait then call handlers as appropriate
1330 // < 0 means error
1331 // 0 means timeout
1332 // > 0 means count of descriptors ready
1333 int n = select(fdmax + 1, &fdsRead, &fdsWrite, NULL, ptvWait);
1334
1335 // If error, return error.
1336 if (n < 0) {
1337 if (errno != EINTR) {
1338 LOG_E(LS_ERROR, EN, errno) << "select";
1339 return false;
1340 }
1341 // Else ignore the error and keep going. If this EINTR was for one of the
1342 // signals managed by this PhysicalSocketServer, the
1343 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1344 // iteration.
1345 } else if (n == 0) {
1346 // If timeout, return success
1347 return true;
1348 } else {
1349 // We have signaled descriptors
1350 CritScope cr(&crit_);
1351 for (size_t i = 0; i < dispatchers_.size(); ++i) {
1352 Dispatcher *pdispatcher = dispatchers_[i];
1353 int fd = pdispatcher->GetDescriptor();
Peter Boström0c4e06b2015-10-07 12:23:21 +02001354 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001355 int errcode = 0;
1356
1357 // Reap any error code, which can be signaled through reads or writes.
jbauch095ae152015-12-18 01:39:55 -08001358 // TODO(pthatcher): Should we set errcode if getsockopt fails?
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001359 if (FD_ISSET(fd, &fdsRead) || FD_ISSET(fd, &fdsWrite)) {
1360 socklen_t len = sizeof(errcode);
1361 ::getsockopt(fd, SOL_SOCKET, SO_ERROR, &errcode, &len);
1362 }
1363
1364 // Check readable descriptors. If we're waiting on an accept, signal
1365 // that. Otherwise we're waiting for data, check to see if we're
1366 // readable or really closed.
jbauch095ae152015-12-18 01:39:55 -08001367 // TODO(pthatcher): Only peek at TCP descriptors.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001368 if (FD_ISSET(fd, &fdsRead)) {
1369 FD_CLR(fd, &fdsRead);
1370 if (pdispatcher->GetRequestedEvents() & DE_ACCEPT) {
1371 ff |= DE_ACCEPT;
1372 } else if (errcode || pdispatcher->IsDescriptorClosed()) {
1373 ff |= DE_CLOSE;
1374 } else {
1375 ff |= DE_READ;
1376 }
1377 }
1378
1379 // Check writable descriptors. If we're waiting on a connect, detect
1380 // success versus failure by the reaped error code.
1381 if (FD_ISSET(fd, &fdsWrite)) {
1382 FD_CLR(fd, &fdsWrite);
1383 if (pdispatcher->GetRequestedEvents() & DE_CONNECT) {
1384 if (!errcode) {
1385 ff |= DE_CONNECT;
1386 } else {
1387 ff |= DE_CLOSE;
1388 }
1389 } else {
1390 ff |= DE_WRITE;
1391 }
1392 }
1393
1394 // Tell the descriptor about the event.
1395 if (ff != 0) {
1396 pdispatcher->OnPreEvent(ff);
1397 pdispatcher->OnEvent(ff, errcode);
1398 }
1399 }
1400 }
1401
1402 // Recalc the time remaining to wait. Doing it here means it doesn't get
1403 // calced twice the first time through the loop
1404 if (ptvWait) {
1405 ptvWait->tv_sec = 0;
1406 ptvWait->tv_usec = 0;
1407 struct timeval tvT;
1408 gettimeofday(&tvT, NULL);
1409 if ((tvStop.tv_sec > tvT.tv_sec)
1410 || ((tvStop.tv_sec == tvT.tv_sec)
1411 && (tvStop.tv_usec > tvT.tv_usec))) {
1412 ptvWait->tv_sec = tvStop.tv_sec - tvT.tv_sec;
1413 ptvWait->tv_usec = tvStop.tv_usec - tvT.tv_usec;
1414 if (ptvWait->tv_usec < 0) {
nisseede5da42017-01-12 05:15:36 -08001415 RTC_DCHECK(ptvWait->tv_sec > 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001416 ptvWait->tv_usec += 1000000;
1417 ptvWait->tv_sec -= 1;
1418 }
1419 }
1420 }
1421 }
1422
1423 return true;
1424}
1425
1426static void GlobalSignalHandler(int signum) {
1427 PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
1428}
1429
1430bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
1431 void (*handler)(int)) {
1432 // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
1433 // otherwise set one.
1434 if (handler == SIG_IGN || handler == SIG_DFL) {
1435 if (!InstallSignal(signum, handler)) {
1436 return false;
1437 }
1438 if (signal_dispatcher_) {
1439 signal_dispatcher_->ClearHandler(signum);
1440 if (!signal_dispatcher_->HasHandlers()) {
1441 signal_dispatcher_.reset();
1442 }
1443 }
1444 } else {
1445 if (!signal_dispatcher_) {
1446 signal_dispatcher_.reset(new PosixSignalDispatcher(this));
1447 }
1448 signal_dispatcher_->SetHandler(signum, handler);
1449 if (!InstallSignal(signum, &GlobalSignalHandler)) {
1450 return false;
1451 }
1452 }
1453 return true;
1454}
1455
1456Dispatcher* PhysicalSocketServer::signal_dispatcher() {
1457 return signal_dispatcher_.get();
1458}
1459
1460bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
1461 struct sigaction act;
1462 // It doesn't really matter what we set this mask to.
1463 if (sigemptyset(&act.sa_mask) != 0) {
1464 LOG_ERR(LS_ERROR) << "Couldn't set mask";
1465 return false;
1466 }
1467 act.sa_handler = handler;
1468#if !defined(__native_client__)
1469 // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
1470 // and it's a nuisance. Though some syscalls still return EINTR and there's no
1471 // real standard for which ones. :(
1472 act.sa_flags = SA_RESTART;
1473#else
1474 act.sa_flags = 0;
1475#endif
1476 if (sigaction(signum, &act, NULL) != 0) {
1477 LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
1478 return false;
1479 }
1480 return true;
1481}
1482#endif // WEBRTC_POSIX
1483
1484#if defined(WEBRTC_WIN)
1485bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
Honghai Zhang82d78622016-05-06 11:29:15 -07001486 int64_t cmsTotal = cmsWait;
1487 int64_t cmsElapsed = 0;
1488 int64_t msStart = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001489
1490 fWait_ = true;
1491 while (fWait_) {
1492 std::vector<WSAEVENT> events;
1493 std::vector<Dispatcher *> event_owners;
1494
1495 events.push_back(socket_ev_);
1496
1497 {
1498 CritScope cr(&crit_);
1499 size_t i = 0;
1500 iterators_.push_back(&i);
1501 // Don't track dispatchers_.size(), because we want to pick up any new
1502 // dispatchers that were added while processing the loop.
1503 while (i < dispatchers_.size()) {
1504 Dispatcher* disp = dispatchers_[i++];
1505 if (!process_io && (disp != signal_wakeup_))
1506 continue;
1507 SOCKET s = disp->GetSocket();
1508 if (disp->CheckSignalClose()) {
1509 // We just signalled close, don't poll this socket
1510 } else if (s != INVALID_SOCKET) {
1511 WSAEventSelect(s,
1512 events[0],
1513 FlagsToEvents(disp->GetRequestedEvents()));
1514 } else {
1515 events.push_back(disp->GetWSAEvent());
1516 event_owners.push_back(disp);
1517 }
1518 }
nisseede5da42017-01-12 05:15:36 -08001519 RTC_DCHECK(iterators_.back() == &i);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001520 iterators_.pop_back();
1521 }
1522
1523 // Which is shorter, the delay wait or the asked wait?
1524
Honghai Zhang82d78622016-05-06 11:29:15 -07001525 int64_t cmsNext;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001526 if (cmsWait == kForever) {
1527 cmsNext = cmsWait;
1528 } else {
Honghai Zhang82d78622016-05-06 11:29:15 -07001529 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001530 }
1531
1532 // Wait for one of the events to signal
1533 DWORD dw = WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()),
1534 &events[0],
1535 false,
Honghai Zhang82d78622016-05-06 11:29:15 -07001536 static_cast<DWORD>(cmsNext),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001537 false);
1538
1539 if (dw == WSA_WAIT_FAILED) {
1540 // Failed?
jbauch095ae152015-12-18 01:39:55 -08001541 // TODO(pthatcher): need a better strategy than this!
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001542 WSAGetLastError();
nissec80e7412017-01-11 05:56:46 -08001543 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001544 return false;
1545 } else if (dw == WSA_WAIT_TIMEOUT) {
1546 // Timeout?
1547 return true;
1548 } else {
1549 // Figure out which one it is and call it
1550 CritScope cr(&crit_);
1551 int index = dw - WSA_WAIT_EVENT_0;
1552 if (index > 0) {
1553 --index; // The first event is the socket event
1554 event_owners[index]->OnPreEvent(0);
1555 event_owners[index]->OnEvent(0, 0);
1556 } else if (process_io) {
1557 size_t i = 0, end = dispatchers_.size();
1558 iterators_.push_back(&i);
1559 iterators_.push_back(&end); // Don't iterate over new dispatchers.
1560 while (i < end) {
1561 Dispatcher* disp = dispatchers_[i++];
1562 SOCKET s = disp->GetSocket();
1563 if (s == INVALID_SOCKET)
1564 continue;
1565
1566 WSANETWORKEVENTS wsaEvents;
1567 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1568 if (err == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001569 {
1570 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1571 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
1572 LOG(WARNING) << "PhysicalSocketServer got FD_READ_BIT error "
1573 << wsaEvents.iErrorCode[FD_READ_BIT];
1574 }
1575 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1576 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
1577 LOG(WARNING) << "PhysicalSocketServer got FD_WRITE_BIT error "
1578 << wsaEvents.iErrorCode[FD_WRITE_BIT];
1579 }
1580 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1581 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
1582 LOG(WARNING) << "PhysicalSocketServer got FD_CONNECT_BIT error "
1583 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
1584 }
1585 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1586 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
1587 LOG(WARNING) << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1588 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
1589 }
1590 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1591 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
1592 LOG(WARNING) << "PhysicalSocketServer got FD_CLOSE_BIT error "
1593 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
1594 }
1595 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001596 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001597 int errcode = 0;
1598 if (wsaEvents.lNetworkEvents & FD_READ)
1599 ff |= DE_READ;
1600 if (wsaEvents.lNetworkEvents & FD_WRITE)
1601 ff |= DE_WRITE;
1602 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1603 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1604 ff |= DE_CONNECT;
1605 } else {
1606 ff |= DE_CLOSE;
1607 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1608 }
1609 }
1610 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1611 ff |= DE_ACCEPT;
1612 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1613 ff |= DE_CLOSE;
1614 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1615 }
1616 if (ff != 0) {
1617 disp->OnPreEvent(ff);
1618 disp->OnEvent(ff, errcode);
1619 }
1620 }
1621 }
nisseede5da42017-01-12 05:15:36 -08001622 RTC_DCHECK(iterators_.back() == &end);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001623 iterators_.pop_back();
nisseede5da42017-01-12 05:15:36 -08001624 RTC_DCHECK(iterators_.back() == &i);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001625 iterators_.pop_back();
1626 }
1627
1628 // Reset the network event until new activity occurs
1629 WSAResetEvent(socket_ev_);
1630 }
1631
1632 // Break?
1633 if (!fWait_)
1634 break;
1635 cmsElapsed = TimeSince(msStart);
1636 if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
1637 break;
1638 }
1639 }
1640
1641 // Done
1642 return true;
1643}
honghaizcec0a082016-01-15 14:49:09 -08001644#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001645
1646} // namespace rtc