blob: 6970388844e4a9475d62a38a0201108ebe43bd47 [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) {
193 sockaddr_storage addr_storage;
194 size_t len = bind_addr.ToSockAddrStorage(&addr_storage);
195 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
196 int err = ::bind(s_, addr, static_cast<int>(len));
197 UpdateLastError();
tfarinaa41ab932015-10-30 16:08:48 -0700198#if !defined(NDEBUG)
jbauch095ae152015-12-18 01:39:55 -0800199 if (0 == err) {
200 dbg_addr_ = "Bound @ ";
201 dbg_addr_.append(GetLocalAddress().ToString());
202 }
tfarinaa41ab932015-10-30 16:08:48 -0700203#endif
honghaizcec0a082016-01-15 14:49:09 -0800204 if (ss_->network_binder()) {
205 int result =
206 ss_->network_binder()->BindSocketToNetwork(s_, bind_addr.ipaddr());
207 if (result < 0) {
208 LOG(LS_INFO) << "Binding socket to network address "
209 << bind_addr.ipaddr().ToString() << " result " << result;
210 }
211 }
jbauch095ae152015-12-18 01:39:55 -0800212 return err;
213}
214
215int PhysicalSocket::Connect(const SocketAddress& addr) {
216 // TODO(pthatcher): Implicit creation is required to reconnect...
217 // ...but should we make it more explicit?
218 if (state_ != CS_CLOSED) {
219 SetError(EALREADY);
220 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000221 }
jbauch095ae152015-12-18 01:39:55 -0800222 if (addr.IsUnresolvedIP()) {
223 LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
224 resolver_ = new AsyncResolver();
225 resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult);
226 resolver_->Start(addr);
227 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000228 return 0;
229 }
230
jbauch095ae152015-12-18 01:39:55 -0800231 return DoConnect(addr);
232}
233
234int PhysicalSocket::DoConnect(const SocketAddress& connect_addr) {
235 if ((s_ == INVALID_SOCKET) &&
236 !Create(connect_addr.family(), SOCK_STREAM)) {
237 return SOCKET_ERROR;
238 }
239 sockaddr_storage addr_storage;
240 size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
241 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
242 int err = ::connect(s_, addr, static_cast<int>(len));
243 UpdateLastError();
244 if (err == 0) {
245 state_ = CS_CONNECTED;
246 } else if (IsBlockingError(GetError())) {
247 state_ = CS_CONNECTING;
248 enabled_events_ |= DE_CONNECT;
249 } else {
250 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000251 }
252
jbauch095ae152015-12-18 01:39:55 -0800253 enabled_events_ |= DE_READ | DE_WRITE;
254 return 0;
255}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000256
jbauch095ae152015-12-18 01:39:55 -0800257int PhysicalSocket::GetError() const {
258 CritScope cs(&crit_);
259 return error_;
260}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000261
jbauch095ae152015-12-18 01:39:55 -0800262void PhysicalSocket::SetError(int error) {
263 CritScope cs(&crit_);
264 error_ = error;
265}
266
267AsyncSocket::ConnState PhysicalSocket::GetState() const {
268 return state_;
269}
270
271int PhysicalSocket::GetOption(Option opt, int* value) {
272 int slevel;
273 int sopt;
274 if (TranslateOption(opt, &slevel, &sopt) == -1)
275 return -1;
276 socklen_t optlen = sizeof(*value);
277 int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
278 if (ret != -1 && opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000279#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800280 *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000281#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000282 }
jbauch095ae152015-12-18 01:39:55 -0800283 return ret;
284}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000285
jbauch095ae152015-12-18 01:39:55 -0800286int PhysicalSocket::SetOption(Option opt, int value) {
287 int slevel;
288 int sopt;
289 if (TranslateOption(opt, &slevel, &sopt) == -1)
290 return -1;
291 if (opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000292#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800293 value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000294#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000295 }
jbauch095ae152015-12-18 01:39:55 -0800296 return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
297}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000298
jbauch095ae152015-12-18 01:39:55 -0800299int PhysicalSocket::Send(const void* pv, size_t cb) {
jbauchf2a2bf42016-02-03 16:45:32 -0800300 int sent = DoSend(s_, reinterpret_cast<const char *>(pv),
301 static_cast<int>(cb),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000302#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800303 // Suppress SIGPIPE. Without this, attempting to send on a socket whose
304 // other end is closed will result in a SIGPIPE signal being raised to
305 // our process, which by default will terminate the process, which we
306 // don't want. By specifying this flag, we'll just get the error EPIPE
307 // instead and can handle the error gracefully.
308 MSG_NOSIGNAL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000309#else
jbauch095ae152015-12-18 01:39:55 -0800310 0
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000311#endif
jbauch095ae152015-12-18 01:39:55 -0800312 );
313 UpdateLastError();
314 MaybeRemapSendError();
315 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800316 RTC_DCHECK(sent <= static_cast<int>(cb));
jbauchf2a2bf42016-02-03 16:45:32 -0800317 if ((sent > 0 && sent < static_cast<int>(cb)) ||
318 (sent < 0 && IsBlockingError(GetError()))) {
jbauch095ae152015-12-18 01:39:55 -0800319 enabled_events_ |= DE_WRITE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000320 }
jbauch095ae152015-12-18 01:39:55 -0800321 return sent;
322}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000323
jbauch095ae152015-12-18 01:39:55 -0800324int PhysicalSocket::SendTo(const void* buffer,
325 size_t length,
326 const SocketAddress& addr) {
327 sockaddr_storage saddr;
328 size_t len = addr.ToSockAddrStorage(&saddr);
jbauchf2a2bf42016-02-03 16:45:32 -0800329 int sent = DoSendTo(
jbauch095ae152015-12-18 01:39:55 -0800330 s_, static_cast<const char *>(buffer), static_cast<int>(length),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000331#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800332 // Suppress SIGPIPE. See above for explanation.
333 MSG_NOSIGNAL,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000334#else
jbauch095ae152015-12-18 01:39:55 -0800335 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000336#endif
jbauch095ae152015-12-18 01:39:55 -0800337 reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
338 UpdateLastError();
339 MaybeRemapSendError();
340 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800341 RTC_DCHECK(sent <= static_cast<int>(length));
jbauchf2a2bf42016-02-03 16:45:32 -0800342 if ((sent > 0 && sent < static_cast<int>(length)) ||
343 (sent < 0 && IsBlockingError(GetError()))) {
jbauch095ae152015-12-18 01:39:55 -0800344 enabled_events_ |= DE_WRITE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000345 }
jbauch095ae152015-12-18 01:39:55 -0800346 return sent;
347}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000348
Stefan Holmer9131efd2016-05-23 18:19:26 +0200349int PhysicalSocket::Recv(void* buffer, size_t length, int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800350 int received = ::recv(s_, static_cast<char*>(buffer),
351 static_cast<int>(length), 0);
352 if ((received == 0) && (length != 0)) {
353 // Note: on graceful shutdown, recv can return 0. In this case, we
354 // pretend it is blocking, and then signal close, so that simplifying
355 // assumptions can be made about Recv.
356 LOG(LS_WARNING) << "EOF from socket; deferring close event";
357 // Must turn this back on so that the select() loop will notice the close
358 // event.
359 enabled_events_ |= DE_READ;
360 SetError(EWOULDBLOCK);
361 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000362 }
Stefan Holmer9131efd2016-05-23 18:19:26 +0200363 if (timestamp) {
364 *timestamp = GetSocketRecvTimestamp(s_);
365 }
jbauch095ae152015-12-18 01:39:55 -0800366 UpdateLastError();
367 int error = GetError();
368 bool success = (received >= 0) || IsBlockingError(error);
369 if (udp_ || success) {
370 enabled_events_ |= DE_READ;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000371 }
jbauch095ae152015-12-18 01:39:55 -0800372 if (!success) {
373 LOG_F(LS_VERBOSE) << "Error = " << error;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000374 }
jbauch095ae152015-12-18 01:39:55 -0800375 return received;
376}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000377
jbauch095ae152015-12-18 01:39:55 -0800378int PhysicalSocket::RecvFrom(void* buffer,
379 size_t length,
Stefan Holmer9131efd2016-05-23 18:19:26 +0200380 SocketAddress* out_addr,
381 int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800382 sockaddr_storage addr_storage;
383 socklen_t addr_len = sizeof(addr_storage);
384 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
385 int received = ::recvfrom(s_, static_cast<char*>(buffer),
386 static_cast<int>(length), 0, addr, &addr_len);
Stefan Holmer9131efd2016-05-23 18:19:26 +0200387 if (timestamp) {
388 *timestamp = GetSocketRecvTimestamp(s_);
389 }
jbauch095ae152015-12-18 01:39:55 -0800390 UpdateLastError();
391 if ((received >= 0) && (out_addr != nullptr))
392 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
393 int error = GetError();
394 bool success = (received >= 0) || IsBlockingError(error);
395 if (udp_ || success) {
396 enabled_events_ |= DE_READ;
397 }
398 if (!success) {
399 LOG_F(LS_VERBOSE) << "Error = " << error;
400 }
401 return received;
402}
403
404int PhysicalSocket::Listen(int backlog) {
405 int err = ::listen(s_, backlog);
406 UpdateLastError();
407 if (err == 0) {
408 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000409 enabled_events_ |= DE_ACCEPT;
jbauch095ae152015-12-18 01:39:55 -0800410#if !defined(NDEBUG)
411 dbg_addr_ = "Listening @ ";
412 dbg_addr_.append(GetLocalAddress().ToString());
413#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000414 }
jbauch095ae152015-12-18 01:39:55 -0800415 return err;
416}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000417
jbauch095ae152015-12-18 01:39:55 -0800418AsyncSocket* PhysicalSocket::Accept(SocketAddress* out_addr) {
419 // Always re-subscribe DE_ACCEPT to make sure new incoming connections will
420 // trigger an event even if DoAccept returns an error here.
421 enabled_events_ |= DE_ACCEPT;
422 sockaddr_storage addr_storage;
423 socklen_t addr_len = sizeof(addr_storage);
424 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
425 SOCKET s = DoAccept(s_, addr, &addr_len);
426 UpdateLastError();
427 if (s == INVALID_SOCKET)
428 return nullptr;
429 if (out_addr != nullptr)
430 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
431 return ss_->WrapSocket(s);
432}
433
434int PhysicalSocket::Close() {
435 if (s_ == INVALID_SOCKET)
436 return 0;
437 int err = ::closesocket(s_);
438 UpdateLastError();
439 s_ = INVALID_SOCKET;
440 state_ = CS_CLOSED;
441 enabled_events_ = 0;
442 if (resolver_) {
443 resolver_->Destroy(false);
444 resolver_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000445 }
jbauch095ae152015-12-18 01:39:55 -0800446 return err;
447}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000448
jbauch095ae152015-12-18 01:39:55 -0800449int PhysicalSocket::EstimateMTU(uint16_t* mtu) {
450 SocketAddress addr = GetRemoteAddress();
451 if (addr.IsAnyIP()) {
452 SetError(ENOTCONN);
453 return -1;
454 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000455
456#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800457 // Gets the interface MTU (TTL=1) for the interface used to reach |addr|.
458 WinPing ping;
459 if (!ping.IsValid()) {
460 SetError(EINVAL); // can't think of a better error ID
461 return -1;
462 }
463 int header_size = ICMP_HEADER_SIZE;
464 if (addr.family() == AF_INET6) {
465 header_size += IPV6_HEADER_SIZE;
466 } else if (addr.family() == AF_INET) {
467 header_size += IP_HEADER_SIZE;
468 }
469
470 for (int level = 0; PACKET_MAXIMUMS[level + 1] > 0; ++level) {
471 int32_t size = PACKET_MAXIMUMS[level] - header_size;
472 WinPing::PingResult result = ping.Ping(addr.ipaddr(), size,
473 ICMP_PING_TIMEOUT_MILLIS,
474 1, false);
475 if (result == WinPing::PING_FAIL) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000476 SetError(EINVAL); // can't think of a better error ID
477 return -1;
jbauch095ae152015-12-18 01:39:55 -0800478 } else if (result != WinPing::PING_TOO_LARGE) {
479 *mtu = PACKET_MAXIMUMS[level];
480 return 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000481 }
jbauch095ae152015-12-18 01:39:55 -0800482 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000483
nissec80e7412017-01-11 05:56:46 -0800484 RTC_NOTREACHED();
jbauch095ae152015-12-18 01:39:55 -0800485 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000486#elif defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800487 // No simple way to do this on Mac OS X.
488 // SIOCGIFMTU would work if we knew which interface would be used, but
489 // figuring that out is pretty complicated. For now we'll return an error
490 // and let the caller pick a default MTU.
491 SetError(EINVAL);
492 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000493#elif defined(WEBRTC_LINUX)
jbauch095ae152015-12-18 01:39:55 -0800494 // Gets the path MTU.
495 int value;
496 socklen_t vlen = sizeof(value);
497 int err = getsockopt(s_, IPPROTO_IP, IP_MTU, &value, &vlen);
498 if (err < 0) {
499 UpdateLastError();
500 return err;
501 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000502
nisseede5da42017-01-12 05:15:36 -0800503 RTC_DCHECK((0 <= value) && (value <= 65536));
jbauch095ae152015-12-18 01:39:55 -0800504 *mtu = value;
505 return 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000506#elif defined(__native_client__)
jbauch095ae152015-12-18 01:39:55 -0800507 // Most socket operations, including this, will fail in NaCl's sandbox.
508 error_ = EACCES;
509 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000510#endif
jbauch095ae152015-12-18 01:39:55 -0800511}
512
jbauch095ae152015-12-18 01:39:55 -0800513SOCKET PhysicalSocket::DoAccept(SOCKET socket,
514 sockaddr* addr,
515 socklen_t* addrlen) {
516 return ::accept(socket, addr, addrlen);
517}
518
jbauchf2a2bf42016-02-03 16:45:32 -0800519int PhysicalSocket::DoSend(SOCKET socket, const char* buf, int len, int flags) {
520 return ::send(socket, buf, len, flags);
521}
522
523int PhysicalSocket::DoSendTo(SOCKET socket,
524 const char* buf,
525 int len,
526 int flags,
527 const struct sockaddr* dest_addr,
528 socklen_t addrlen) {
529 return ::sendto(socket, buf, len, flags, dest_addr, addrlen);
530}
531
jbauch095ae152015-12-18 01:39:55 -0800532void PhysicalSocket::OnResolveResult(AsyncResolverInterface* resolver) {
533 if (resolver != resolver_) {
534 return;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000535 }
536
jbauch095ae152015-12-18 01:39:55 -0800537 int error = resolver_->GetError();
538 if (error == 0) {
539 error = DoConnect(resolver_->address());
540 } else {
541 Close();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000542 }
543
jbauch095ae152015-12-18 01:39:55 -0800544 if (error) {
545 SetError(error);
546 SignalCloseEvent(this, error);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000547 }
jbauch095ae152015-12-18 01:39:55 -0800548}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000549
jbauch095ae152015-12-18 01:39:55 -0800550void PhysicalSocket::UpdateLastError() {
551 SetError(LAST_SYSTEM_ERROR);
552}
553
554void PhysicalSocket::MaybeRemapSendError() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000555#if defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800556 // https://developer.apple.com/library/mac/documentation/Darwin/
557 // Reference/ManPages/man2/sendto.2.html
558 // ENOBUFS - The output queue for a network interface is full.
559 // This generally indicates that the interface has stopped sending,
560 // but may be caused by transient congestion.
561 if (GetError() == ENOBUFS) {
562 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000563 }
jbauch095ae152015-12-18 01:39:55 -0800564#endif
565}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000566
jbauch095ae152015-12-18 01:39:55 -0800567int PhysicalSocket::TranslateOption(Option opt, int* slevel, int* sopt) {
568 switch (opt) {
569 case OPT_DONTFRAGMENT:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000570#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800571 *slevel = IPPROTO_IP;
572 *sopt = IP_DONTFRAGMENT;
573 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000574#elif defined(WEBRTC_MAC) || defined(BSD) || defined(__native_client__)
jbauch095ae152015-12-18 01:39:55 -0800575 LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
576 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000577#elif defined(WEBRTC_POSIX)
jbauch095ae152015-12-18 01:39:55 -0800578 *slevel = IPPROTO_IP;
579 *sopt = IP_MTU_DISCOVER;
580 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000581#endif
jbauch095ae152015-12-18 01:39:55 -0800582 case OPT_RCVBUF:
583 *slevel = SOL_SOCKET;
584 *sopt = SO_RCVBUF;
585 break;
586 case OPT_SNDBUF:
587 *slevel = SOL_SOCKET;
588 *sopt = SO_SNDBUF;
589 break;
590 case OPT_NODELAY:
591 *slevel = IPPROTO_TCP;
592 *sopt = TCP_NODELAY;
593 break;
594 case OPT_DSCP:
595 LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
596 return -1;
597 case OPT_RTP_SENDTIME_EXTN_ID:
598 return -1; // No logging is necessary as this not a OS socket option.
599 default:
nissec80e7412017-01-11 05:56:46 -0800600 RTC_NOTREACHED();
jbauch095ae152015-12-18 01:39:55 -0800601 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000602 }
jbauch095ae152015-12-18 01:39:55 -0800603 return 0;
604}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000605
jbauch4331fcd2016-01-06 22:20:28 -0800606SocketDispatcher::SocketDispatcher(PhysicalSocketServer *ss)
607#if defined(WEBRTC_WIN)
608 : PhysicalSocket(ss), id_(0), signal_close_(false)
609#else
610 : PhysicalSocket(ss)
611#endif
612{
613}
614
615SocketDispatcher::SocketDispatcher(SOCKET s, PhysicalSocketServer *ss)
616#if defined(WEBRTC_WIN)
617 : PhysicalSocket(ss, s), id_(0), signal_close_(false)
618#else
619 : PhysicalSocket(ss, s)
620#endif
621{
622}
623
624SocketDispatcher::~SocketDispatcher() {
625 Close();
626}
627
628bool SocketDispatcher::Initialize() {
nisseede5da42017-01-12 05:15:36 -0800629 RTC_DCHECK(s_ != INVALID_SOCKET);
jbauch4331fcd2016-01-06 22:20:28 -0800630 // Must be a non-blocking
631#if defined(WEBRTC_WIN)
632 u_long argp = 1;
633 ioctlsocket(s_, FIONBIO, &argp);
634#elif defined(WEBRTC_POSIX)
635 fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
636#endif
637 ss_->Add(this);
638 return true;
639}
640
641bool SocketDispatcher::Create(int type) {
642 return Create(AF_INET, type);
643}
644
645bool SocketDispatcher::Create(int family, int type) {
646 // Change the socket to be non-blocking.
647 if (!PhysicalSocket::Create(family, type))
648 return false;
649
650 if (!Initialize())
651 return false;
652
653#if defined(WEBRTC_WIN)
654 do { id_ = ++next_id_; } while (id_ == 0);
655#endif
656 return true;
657}
658
659#if defined(WEBRTC_WIN)
660
661WSAEVENT SocketDispatcher::GetWSAEvent() {
662 return WSA_INVALID_EVENT;
663}
664
665SOCKET SocketDispatcher::GetSocket() {
666 return s_;
667}
668
669bool SocketDispatcher::CheckSignalClose() {
670 if (!signal_close_)
671 return false;
672
673 char ch;
674 if (recv(s_, &ch, 1, MSG_PEEK) > 0)
675 return false;
676
677 state_ = CS_CLOSED;
678 signal_close_ = false;
679 SignalCloseEvent(this, signal_err_);
680 return true;
681}
682
683int SocketDispatcher::next_id_ = 0;
684
685#elif defined(WEBRTC_POSIX)
686
687int SocketDispatcher::GetDescriptor() {
688 return s_;
689}
690
691bool SocketDispatcher::IsDescriptorClosed() {
692 // We don't have a reliable way of distinguishing end-of-stream
693 // from readability. So test on each readable call. Is this
694 // inefficient? Probably.
695 char ch;
696 ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
697 if (res > 0) {
698 // Data available, so not closed.
699 return false;
700 } else if (res == 0) {
701 // EOF, so closed.
702 return true;
703 } else { // error
704 switch (errno) {
705 // Returned if we've already closed s_.
706 case EBADF:
707 // Returned during ungraceful peer shutdown.
708 case ECONNRESET:
709 return true;
710 default:
711 // Assume that all other errors are just blocking errors, meaning the
712 // connection is still good but we just can't read from it right now.
713 // This should only happen when connecting (and at most once), because
714 // in all other cases this function is only called if the file
715 // descriptor is already known to be in the readable state. However,
716 // it's not necessary a problem if we spuriously interpret a
717 // "connection lost"-type error as a blocking error, because typically
718 // the next recv() will get EOF, so we'll still eventually notice that
719 // the socket is closed.
720 LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
721 return false;
722 }
723 }
724}
725
726#endif // WEBRTC_POSIX
727
728uint32_t SocketDispatcher::GetRequestedEvents() {
729 return enabled_events_;
730}
731
732void SocketDispatcher::OnPreEvent(uint32_t ff) {
733 if ((ff & DE_CONNECT) != 0)
734 state_ = CS_CONNECTED;
735
736#if defined(WEBRTC_WIN)
737 // We set CS_CLOSED from CheckSignalClose.
738#elif defined(WEBRTC_POSIX)
739 if ((ff & DE_CLOSE) != 0)
740 state_ = CS_CLOSED;
741#endif
742}
743
744#if defined(WEBRTC_WIN)
745
746void SocketDispatcher::OnEvent(uint32_t ff, int err) {
747 int cache_id = id_;
748 // Make sure we deliver connect/accept first. Otherwise, consumers may see
749 // something like a READ followed by a CONNECT, which would be odd.
750 if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
751 if (ff != DE_CONNECT)
752 LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
753 enabled_events_ &= ~DE_CONNECT;
754#if !defined(NDEBUG)
755 dbg_addr_ = "Connected @ ";
756 dbg_addr_.append(GetRemoteAddress().ToString());
757#endif
758 SignalConnectEvent(this);
759 }
760 if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
761 enabled_events_ &= ~DE_ACCEPT;
762 SignalReadEvent(this);
763 }
764 if ((ff & DE_READ) != 0) {
765 enabled_events_ &= ~DE_READ;
766 SignalReadEvent(this);
767 }
768 if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
769 enabled_events_ &= ~DE_WRITE;
770 SignalWriteEvent(this);
771 }
772 if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
773 signal_close_ = true;
774 signal_err_ = err;
775 }
776}
777
778#elif defined(WEBRTC_POSIX)
779
780void SocketDispatcher::OnEvent(uint32_t ff, int err) {
781 // Make sure we deliver connect/accept first. Otherwise, consumers may see
782 // something like a READ followed by a CONNECT, which would be odd.
783 if ((ff & DE_CONNECT) != 0) {
784 enabled_events_ &= ~DE_CONNECT;
785 SignalConnectEvent(this);
786 }
787 if ((ff & DE_ACCEPT) != 0) {
788 enabled_events_ &= ~DE_ACCEPT;
789 SignalReadEvent(this);
790 }
791 if ((ff & DE_READ) != 0) {
792 enabled_events_ &= ~DE_READ;
793 SignalReadEvent(this);
794 }
795 if ((ff & DE_WRITE) != 0) {
796 enabled_events_ &= ~DE_WRITE;
797 SignalWriteEvent(this);
798 }
799 if ((ff & DE_CLOSE) != 0) {
800 // The socket is now dead to us, so stop checking it.
801 enabled_events_ = 0;
802 SignalCloseEvent(this, err);
803 }
804}
805
806#endif // WEBRTC_POSIX
807
808int SocketDispatcher::Close() {
809 if (s_ == INVALID_SOCKET)
810 return 0;
811
812#if defined(WEBRTC_WIN)
813 id_ = 0;
814 signal_close_ = false;
815#endif
816 ss_->Remove(this);
817 return PhysicalSocket::Close();
818}
819
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000820#if defined(WEBRTC_POSIX)
821class EventDispatcher : public Dispatcher {
822 public:
823 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
824 if (pipe(afd_) < 0)
825 LOG(LERROR) << "pipe failed";
826 ss_->Add(this);
827 }
828
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000829 ~EventDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000830 ss_->Remove(this);
831 close(afd_[0]);
832 close(afd_[1]);
833 }
834
835 virtual void Signal() {
836 CritScope cs(&crit_);
837 if (!fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200838 const uint8_t b[1] = {0};
nissec16fa5e2017-02-07 07:18:43 -0800839 const ssize_t res = write(afd_[1], b, sizeof(b));
840 RTC_DCHECK_EQ(1, res);
841 fSignaled_ = true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000842 }
843 }
844
Peter Boström0c4e06b2015-10-07 12:23:21 +0200845 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000846
Peter Boström0c4e06b2015-10-07 12:23:21 +0200847 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000848 // It is not possible to perfectly emulate an auto-resetting event with
849 // pipes. This simulates it by resetting before the event is handled.
850
851 CritScope cs(&crit_);
852 if (fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200853 uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
nissec16fa5e2017-02-07 07:18:43 -0800854 const ssize_t res = read(afd_[0], b, sizeof(b));
855 RTC_DCHECK_EQ(1, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000856 fSignaled_ = false;
857 }
858 }
859
nissec80e7412017-01-11 05:56:46 -0800860 void OnEvent(uint32_t ff, int err) override { RTC_NOTREACHED(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000861
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000862 int GetDescriptor() override { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000863
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000864 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000865
866 private:
867 PhysicalSocketServer *ss_;
868 int afd_[2];
869 bool fSignaled_;
870 CriticalSection crit_;
871};
872
873// These two classes use the self-pipe trick to deliver POSIX signals to our
874// select loop. This is the only safe, reliable, cross-platform way to do
875// non-trivial things with a POSIX signal in an event-driven program (until
876// proper pselect() implementations become ubiquitous).
877
878class PosixSignalHandler {
879 public:
880 // POSIX only specifies 32 signals, but in principle the system might have
881 // more and the programmer might choose to use them, so we size our array
882 // for 128.
883 static const int kNumPosixSignals = 128;
884
885 // There is just a single global instance. (Signal handlers do not get any
886 // sort of user-defined void * parameter, so they can't access anything that
887 // isn't global.)
888 static PosixSignalHandler* Instance() {
Andrew MacDonald469c2c02015-05-22 17:50:26 -0700889 RTC_DEFINE_STATIC_LOCAL(PosixSignalHandler, instance, ());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000890 return &instance;
891 }
892
893 // Returns true if the given signal number is set.
894 bool IsSignalSet(int signum) const {
nisseede5da42017-01-12 05:15:36 -0800895 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800896 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000897 return received_signal_[signum];
898 } else {
899 return false;
900 }
901 }
902
903 // Clears the given signal number.
904 void ClearSignal(int signum) {
nisseede5da42017-01-12 05:15:36 -0800905 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800906 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000907 received_signal_[signum] = false;
908 }
909 }
910
911 // Returns the file descriptor to monitor for signal events.
912 int GetDescriptor() const {
913 return afd_[0];
914 }
915
916 // This is called directly from our real signal handler, so it must be
917 // signal-handler-safe. That means it cannot assume anything about the
918 // user-level state of the process, since the handler could be executed at any
919 // time on any thread.
920 void OnPosixSignalReceived(int signum) {
tfarina5237aaf2015-11-10 23:44:30 -0800921 if (signum >= static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000922 // We don't have space in our array for this.
923 return;
924 }
925 // Set a flag saying we've seen this signal.
926 received_signal_[signum] = true;
927 // Notify application code that we got a signal.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200928 const uint8_t b[1] = {0};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000929 if (-1 == write(afd_[1], b, sizeof(b))) {
930 // Nothing we can do here. If there's an error somehow then there's
931 // nothing we can safely do from a signal handler.
932 // No, we can't even safely log it.
933 // But, we still have to check the return value here. Otherwise,
934 // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
935 return;
936 }
937 }
938
939 private:
940 PosixSignalHandler() {
941 if (pipe(afd_) < 0) {
942 LOG_ERR(LS_ERROR) << "pipe failed";
943 return;
944 }
945 if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
946 LOG_ERR(LS_WARNING) << "fcntl #1 failed";
947 }
948 if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
949 LOG_ERR(LS_WARNING) << "fcntl #2 failed";
950 }
951 memset(const_cast<void *>(static_cast<volatile void *>(received_signal_)),
952 0,
953 sizeof(received_signal_));
954 }
955
956 ~PosixSignalHandler() {
957 int fd1 = afd_[0];
958 int fd2 = afd_[1];
959 // We clobber the stored file descriptor numbers here or else in principle
960 // a signal that happens to be delivered during application termination
961 // could erroneously write a zero byte to an unrelated file handle in
962 // OnPosixSignalReceived() if some other file happens to be opened later
963 // during shutdown and happens to be given the same file descriptor number
964 // as our pipe had. Unfortunately even with this precaution there is still a
965 // race where that could occur if said signal happens to be handled
966 // concurrently with this code and happens to have already read the value of
967 // afd_[1] from memory before we clobber it, but that's unlikely.
968 afd_[0] = -1;
969 afd_[1] = -1;
970 close(fd1);
971 close(fd2);
972 }
973
974 int afd_[2];
975 // These are boolean flags that will be set in our signal handler and read
976 // and cleared from Wait(). There is a race involved in this, but it is
977 // benign. The signal handler sets the flag before signaling the pipe, so
978 // we'll never end up blocking in select() while a flag is still true.
979 // However, if two of the same signal arrive close to each other then it's
980 // possible that the second time the handler may set the flag while it's still
981 // true, meaning that signal will be missed. But the first occurrence of it
982 // will still be handled, so this isn't a problem.
983 // Volatile is not necessary here for correctness, but this data _is_ volatile
984 // so I've marked it as such.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200985 volatile uint8_t received_signal_[kNumPosixSignals];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000986};
987
988class PosixSignalDispatcher : public Dispatcher {
989 public:
990 PosixSignalDispatcher(PhysicalSocketServer *owner) : owner_(owner) {
991 owner_->Add(this);
992 }
993
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000994 ~PosixSignalDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000995 owner_->Remove(this);
996 }
997
Peter Boström0c4e06b2015-10-07 12:23:21 +0200998 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000999
Peter Boström0c4e06b2015-10-07 12:23:21 +02001000 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001001 // Events might get grouped if signals come very fast, so we read out up to
1002 // 16 bytes to make sure we keep the pipe empty.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001003 uint8_t b[16];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001004 ssize_t ret = read(GetDescriptor(), b, sizeof(b));
1005 if (ret < 0) {
1006 LOG_ERR(LS_WARNING) << "Error in read()";
1007 } else if (ret == 0) {
1008 LOG(LS_WARNING) << "Should have read at least one byte";
1009 }
1010 }
1011
Peter Boström0c4e06b2015-10-07 12:23:21 +02001012 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001013 for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
1014 ++signum) {
1015 if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
1016 PosixSignalHandler::Instance()->ClearSignal(signum);
1017 HandlerMap::iterator i = handlers_.find(signum);
1018 if (i == handlers_.end()) {
1019 // This can happen if a signal is delivered to our process at around
1020 // the same time as we unset our handler for it. It is not an error
1021 // condition, but it's unusual enough to be worth logging.
1022 LOG(LS_INFO) << "Received signal with no handler: " << signum;
1023 } else {
1024 // Otherwise, execute our handler.
1025 (*i->second)(signum);
1026 }
1027 }
1028 }
1029 }
1030
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001031 int GetDescriptor() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001032 return PosixSignalHandler::Instance()->GetDescriptor();
1033 }
1034
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001035 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001036
1037 void SetHandler(int signum, void (*handler)(int)) {
1038 handlers_[signum] = handler;
1039 }
1040
1041 void ClearHandler(int signum) {
1042 handlers_.erase(signum);
1043 }
1044
1045 bool HasHandlers() {
1046 return !handlers_.empty();
1047 }
1048
1049 private:
1050 typedef std::map<int, void (*)(int)> HandlerMap;
1051
1052 HandlerMap handlers_;
1053 // Our owner.
1054 PhysicalSocketServer *owner_;
1055};
1056
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001057#endif // WEBRTC_POSIX
1058
1059#if defined(WEBRTC_WIN)
Peter Boström0c4e06b2015-10-07 12:23:21 +02001060static uint32_t FlagsToEvents(uint32_t events) {
1061 uint32_t ffFD = FD_CLOSE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001062 if (events & DE_READ)
1063 ffFD |= FD_READ;
1064 if (events & DE_WRITE)
1065 ffFD |= FD_WRITE;
1066 if (events & DE_CONNECT)
1067 ffFD |= FD_CONNECT;
1068 if (events & DE_ACCEPT)
1069 ffFD |= FD_ACCEPT;
1070 return ffFD;
1071}
1072
1073class EventDispatcher : public Dispatcher {
1074 public:
1075 EventDispatcher(PhysicalSocketServer *ss) : ss_(ss) {
1076 hev_ = WSACreateEvent();
1077 if (hev_) {
1078 ss_->Add(this);
1079 }
1080 }
1081
1082 ~EventDispatcher() {
1083 if (hev_ != NULL) {
1084 ss_->Remove(this);
1085 WSACloseEvent(hev_);
1086 hev_ = NULL;
1087 }
1088 }
1089
1090 virtual void Signal() {
1091 if (hev_ != NULL)
1092 WSASetEvent(hev_);
1093 }
1094
Peter Boström0c4e06b2015-10-07 12:23:21 +02001095 virtual uint32_t GetRequestedEvents() { return 0; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001096
Peter Boström0c4e06b2015-10-07 12:23:21 +02001097 virtual void OnPreEvent(uint32_t ff) { WSAResetEvent(hev_); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001098
Peter Boström0c4e06b2015-10-07 12:23:21 +02001099 virtual void OnEvent(uint32_t ff, int err) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001100
1101 virtual WSAEVENT GetWSAEvent() {
1102 return hev_;
1103 }
1104
1105 virtual SOCKET GetSocket() {
1106 return INVALID_SOCKET;
1107 }
1108
1109 virtual bool CheckSignalClose() { return false; }
1110
1111private:
1112 PhysicalSocketServer* ss_;
1113 WSAEVENT hev_;
1114};
honghaizcec0a082016-01-15 14:49:09 -08001115#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001116
1117// Sets the value of a boolean value to false when signaled.
1118class Signaler : public EventDispatcher {
1119 public:
1120 Signaler(PhysicalSocketServer* ss, bool* pf)
1121 : EventDispatcher(ss), pf_(pf) {
1122 }
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001123 ~Signaler() override { }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001124
Peter Boström0c4e06b2015-10-07 12:23:21 +02001125 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001126 if (pf_)
1127 *pf_ = false;
1128 }
1129
1130 private:
1131 bool *pf_;
1132};
1133
1134PhysicalSocketServer::PhysicalSocketServer()
1135 : fWait_(false) {
1136 signal_wakeup_ = new Signaler(this, &fWait_);
1137#if defined(WEBRTC_WIN)
1138 socket_ev_ = WSACreateEvent();
1139#endif
1140}
1141
1142PhysicalSocketServer::~PhysicalSocketServer() {
1143#if defined(WEBRTC_WIN)
1144 WSACloseEvent(socket_ev_);
1145#endif
1146#if defined(WEBRTC_POSIX)
1147 signal_dispatcher_.reset();
1148#endif
1149 delete signal_wakeup_;
nisseede5da42017-01-12 05:15:36 -08001150 RTC_DCHECK(dispatchers_.empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001151}
1152
1153void PhysicalSocketServer::WakeUp() {
1154 signal_wakeup_->Signal();
1155}
1156
1157Socket* PhysicalSocketServer::CreateSocket(int type) {
1158 return CreateSocket(AF_INET, type);
1159}
1160
1161Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
1162 PhysicalSocket* socket = new PhysicalSocket(this);
1163 if (socket->Create(family, type)) {
1164 return socket;
1165 } else {
1166 delete socket;
jbauch095ae152015-12-18 01:39:55 -08001167 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001168 }
1169}
1170
1171AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int type) {
1172 return CreateAsyncSocket(AF_INET, type);
1173}
1174
1175AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
1176 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1177 if (dispatcher->Create(family, type)) {
1178 return dispatcher;
1179 } else {
1180 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001181 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001182 }
1183}
1184
1185AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
1186 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1187 if (dispatcher->Initialize()) {
1188 return dispatcher;
1189 } else {
1190 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001191 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001192 }
1193}
1194
1195void PhysicalSocketServer::Add(Dispatcher *pdispatcher) {
1196 CritScope cs(&crit_);
1197 // Prevent duplicates. This can cause dead dispatchers to stick around.
1198 DispatcherList::iterator pos = std::find(dispatchers_.begin(),
1199 dispatchers_.end(),
1200 pdispatcher);
1201 if (pos != dispatchers_.end())
1202 return;
1203 dispatchers_.push_back(pdispatcher);
1204}
1205
1206void PhysicalSocketServer::Remove(Dispatcher *pdispatcher) {
1207 CritScope cs(&crit_);
1208 DispatcherList::iterator pos = std::find(dispatchers_.begin(),
1209 dispatchers_.end(),
1210 pdispatcher);
1211 // We silently ignore duplicate calls to Add, so we should silently ignore
1212 // the (expected) symmetric calls to Remove. Note that this may still hide
1213 // a real issue, so we at least log a warning about it.
1214 if (pos == dispatchers_.end()) {
1215 LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
1216 << "dispatcher, potentially from a duplicate call to Add.";
1217 return;
1218 }
1219 size_t index = pos - dispatchers_.begin();
1220 dispatchers_.erase(pos);
1221 for (IteratorList::iterator it = iterators_.begin(); it != iterators_.end();
1222 ++it) {
1223 if (index < **it) {
1224 --**it;
1225 }
1226 }
1227}
1228
1229#if defined(WEBRTC_POSIX)
1230bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
1231 // Calculate timing information
1232
1233 struct timeval *ptvWait = NULL;
1234 struct timeval tvWait;
1235 struct timeval tvStop;
1236 if (cmsWait != kForever) {
1237 // Calculate wait timeval
1238 tvWait.tv_sec = cmsWait / 1000;
1239 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1240 ptvWait = &tvWait;
1241
1242 // Calculate when to return in a timeval
1243 gettimeofday(&tvStop, NULL);
1244 tvStop.tv_sec += tvWait.tv_sec;
1245 tvStop.tv_usec += tvWait.tv_usec;
1246 if (tvStop.tv_usec >= 1000000) {
1247 tvStop.tv_usec -= 1000000;
1248 tvStop.tv_sec += 1;
1249 }
1250 }
1251
1252 // Zero all fd_sets. Don't need to do this inside the loop since
1253 // select() zeros the descriptors not signaled
1254
1255 fd_set fdsRead;
1256 FD_ZERO(&fdsRead);
1257 fd_set fdsWrite;
1258 FD_ZERO(&fdsWrite);
pbos@webrtc.org27e58982014-10-07 17:56:53 +00001259 // Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1260 // inline assembly in FD_ZERO.
1261 // http://crbug.com/344505
1262#ifdef MEMORY_SANITIZER
1263 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1264 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1265#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001266
1267 fWait_ = true;
1268
1269 while (fWait_) {
1270 int fdmax = -1;
1271 {
1272 CritScope cr(&crit_);
1273 for (size_t i = 0; i < dispatchers_.size(); ++i) {
1274 // Query dispatchers for read and write wait state
1275 Dispatcher *pdispatcher = dispatchers_[i];
nisseede5da42017-01-12 05:15:36 -08001276 RTC_DCHECK(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001277 if (!process_io && (pdispatcher != signal_wakeup_))
1278 continue;
1279 int fd = pdispatcher->GetDescriptor();
1280 if (fd > fdmax)
1281 fdmax = fd;
1282
Peter Boström0c4e06b2015-10-07 12:23:21 +02001283 uint32_t ff = pdispatcher->GetRequestedEvents();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001284 if (ff & (DE_READ | DE_ACCEPT))
1285 FD_SET(fd, &fdsRead);
1286 if (ff & (DE_WRITE | DE_CONNECT))
1287 FD_SET(fd, &fdsWrite);
1288 }
1289 }
1290
1291 // Wait then call handlers as appropriate
1292 // < 0 means error
1293 // 0 means timeout
1294 // > 0 means count of descriptors ready
1295 int n = select(fdmax + 1, &fdsRead, &fdsWrite, NULL, ptvWait);
1296
1297 // If error, return error.
1298 if (n < 0) {
1299 if (errno != EINTR) {
1300 LOG_E(LS_ERROR, EN, errno) << "select";
1301 return false;
1302 }
1303 // Else ignore the error and keep going. If this EINTR was for one of the
1304 // signals managed by this PhysicalSocketServer, the
1305 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1306 // iteration.
1307 } else if (n == 0) {
1308 // If timeout, return success
1309 return true;
1310 } else {
1311 // We have signaled descriptors
1312 CritScope cr(&crit_);
1313 for (size_t i = 0; i < dispatchers_.size(); ++i) {
1314 Dispatcher *pdispatcher = dispatchers_[i];
1315 int fd = pdispatcher->GetDescriptor();
Peter Boström0c4e06b2015-10-07 12:23:21 +02001316 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001317 int errcode = 0;
1318
1319 // Reap any error code, which can be signaled through reads or writes.
jbauch095ae152015-12-18 01:39:55 -08001320 // TODO(pthatcher): Should we set errcode if getsockopt fails?
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001321 if (FD_ISSET(fd, &fdsRead) || FD_ISSET(fd, &fdsWrite)) {
1322 socklen_t len = sizeof(errcode);
1323 ::getsockopt(fd, SOL_SOCKET, SO_ERROR, &errcode, &len);
1324 }
1325
1326 // Check readable descriptors. If we're waiting on an accept, signal
1327 // that. Otherwise we're waiting for data, check to see if we're
1328 // readable or really closed.
jbauch095ae152015-12-18 01:39:55 -08001329 // TODO(pthatcher): Only peek at TCP descriptors.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001330 if (FD_ISSET(fd, &fdsRead)) {
1331 FD_CLR(fd, &fdsRead);
1332 if (pdispatcher->GetRequestedEvents() & DE_ACCEPT) {
1333 ff |= DE_ACCEPT;
1334 } else if (errcode || pdispatcher->IsDescriptorClosed()) {
1335 ff |= DE_CLOSE;
1336 } else {
1337 ff |= DE_READ;
1338 }
1339 }
1340
1341 // Check writable descriptors. If we're waiting on a connect, detect
1342 // success versus failure by the reaped error code.
1343 if (FD_ISSET(fd, &fdsWrite)) {
1344 FD_CLR(fd, &fdsWrite);
1345 if (pdispatcher->GetRequestedEvents() & DE_CONNECT) {
1346 if (!errcode) {
1347 ff |= DE_CONNECT;
1348 } else {
1349 ff |= DE_CLOSE;
1350 }
1351 } else {
1352 ff |= DE_WRITE;
1353 }
1354 }
1355
1356 // Tell the descriptor about the event.
1357 if (ff != 0) {
1358 pdispatcher->OnPreEvent(ff);
1359 pdispatcher->OnEvent(ff, errcode);
1360 }
1361 }
1362 }
1363
1364 // Recalc the time remaining to wait. Doing it here means it doesn't get
1365 // calced twice the first time through the loop
1366 if (ptvWait) {
1367 ptvWait->tv_sec = 0;
1368 ptvWait->tv_usec = 0;
1369 struct timeval tvT;
1370 gettimeofday(&tvT, NULL);
1371 if ((tvStop.tv_sec > tvT.tv_sec)
1372 || ((tvStop.tv_sec == tvT.tv_sec)
1373 && (tvStop.tv_usec > tvT.tv_usec))) {
1374 ptvWait->tv_sec = tvStop.tv_sec - tvT.tv_sec;
1375 ptvWait->tv_usec = tvStop.tv_usec - tvT.tv_usec;
1376 if (ptvWait->tv_usec < 0) {
nisseede5da42017-01-12 05:15:36 -08001377 RTC_DCHECK(ptvWait->tv_sec > 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001378 ptvWait->tv_usec += 1000000;
1379 ptvWait->tv_sec -= 1;
1380 }
1381 }
1382 }
1383 }
1384
1385 return true;
1386}
1387
1388static void GlobalSignalHandler(int signum) {
1389 PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
1390}
1391
1392bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
1393 void (*handler)(int)) {
1394 // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
1395 // otherwise set one.
1396 if (handler == SIG_IGN || handler == SIG_DFL) {
1397 if (!InstallSignal(signum, handler)) {
1398 return false;
1399 }
1400 if (signal_dispatcher_) {
1401 signal_dispatcher_->ClearHandler(signum);
1402 if (!signal_dispatcher_->HasHandlers()) {
1403 signal_dispatcher_.reset();
1404 }
1405 }
1406 } else {
1407 if (!signal_dispatcher_) {
1408 signal_dispatcher_.reset(new PosixSignalDispatcher(this));
1409 }
1410 signal_dispatcher_->SetHandler(signum, handler);
1411 if (!InstallSignal(signum, &GlobalSignalHandler)) {
1412 return false;
1413 }
1414 }
1415 return true;
1416}
1417
1418Dispatcher* PhysicalSocketServer::signal_dispatcher() {
1419 return signal_dispatcher_.get();
1420}
1421
1422bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
1423 struct sigaction act;
1424 // It doesn't really matter what we set this mask to.
1425 if (sigemptyset(&act.sa_mask) != 0) {
1426 LOG_ERR(LS_ERROR) << "Couldn't set mask";
1427 return false;
1428 }
1429 act.sa_handler = handler;
1430#if !defined(__native_client__)
1431 // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
1432 // and it's a nuisance. Though some syscalls still return EINTR and there's no
1433 // real standard for which ones. :(
1434 act.sa_flags = SA_RESTART;
1435#else
1436 act.sa_flags = 0;
1437#endif
1438 if (sigaction(signum, &act, NULL) != 0) {
1439 LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
1440 return false;
1441 }
1442 return true;
1443}
1444#endif // WEBRTC_POSIX
1445
1446#if defined(WEBRTC_WIN)
1447bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
Honghai Zhang82d78622016-05-06 11:29:15 -07001448 int64_t cmsTotal = cmsWait;
1449 int64_t cmsElapsed = 0;
1450 int64_t msStart = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001451
1452 fWait_ = true;
1453 while (fWait_) {
1454 std::vector<WSAEVENT> events;
1455 std::vector<Dispatcher *> event_owners;
1456
1457 events.push_back(socket_ev_);
1458
1459 {
1460 CritScope cr(&crit_);
1461 size_t i = 0;
1462 iterators_.push_back(&i);
1463 // Don't track dispatchers_.size(), because we want to pick up any new
1464 // dispatchers that were added while processing the loop.
1465 while (i < dispatchers_.size()) {
1466 Dispatcher* disp = dispatchers_[i++];
1467 if (!process_io && (disp != signal_wakeup_))
1468 continue;
1469 SOCKET s = disp->GetSocket();
1470 if (disp->CheckSignalClose()) {
1471 // We just signalled close, don't poll this socket
1472 } else if (s != INVALID_SOCKET) {
1473 WSAEventSelect(s,
1474 events[0],
1475 FlagsToEvents(disp->GetRequestedEvents()));
1476 } else {
1477 events.push_back(disp->GetWSAEvent());
1478 event_owners.push_back(disp);
1479 }
1480 }
nisseede5da42017-01-12 05:15:36 -08001481 RTC_DCHECK(iterators_.back() == &i);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001482 iterators_.pop_back();
1483 }
1484
1485 // Which is shorter, the delay wait or the asked wait?
1486
Honghai Zhang82d78622016-05-06 11:29:15 -07001487 int64_t cmsNext;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001488 if (cmsWait == kForever) {
1489 cmsNext = cmsWait;
1490 } else {
Honghai Zhang82d78622016-05-06 11:29:15 -07001491 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001492 }
1493
1494 // Wait for one of the events to signal
1495 DWORD dw = WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()),
1496 &events[0],
1497 false,
Honghai Zhang82d78622016-05-06 11:29:15 -07001498 static_cast<DWORD>(cmsNext),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001499 false);
1500
1501 if (dw == WSA_WAIT_FAILED) {
1502 // Failed?
jbauch095ae152015-12-18 01:39:55 -08001503 // TODO(pthatcher): need a better strategy than this!
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001504 WSAGetLastError();
nissec80e7412017-01-11 05:56:46 -08001505 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001506 return false;
1507 } else if (dw == WSA_WAIT_TIMEOUT) {
1508 // Timeout?
1509 return true;
1510 } else {
1511 // Figure out which one it is and call it
1512 CritScope cr(&crit_);
1513 int index = dw - WSA_WAIT_EVENT_0;
1514 if (index > 0) {
1515 --index; // The first event is the socket event
1516 event_owners[index]->OnPreEvent(0);
1517 event_owners[index]->OnEvent(0, 0);
1518 } else if (process_io) {
1519 size_t i = 0, end = dispatchers_.size();
1520 iterators_.push_back(&i);
1521 iterators_.push_back(&end); // Don't iterate over new dispatchers.
1522 while (i < end) {
1523 Dispatcher* disp = dispatchers_[i++];
1524 SOCKET s = disp->GetSocket();
1525 if (s == INVALID_SOCKET)
1526 continue;
1527
1528 WSANETWORKEVENTS wsaEvents;
1529 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1530 if (err == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001531 {
1532 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1533 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
1534 LOG(WARNING) << "PhysicalSocketServer got FD_READ_BIT error "
1535 << wsaEvents.iErrorCode[FD_READ_BIT];
1536 }
1537 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1538 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
1539 LOG(WARNING) << "PhysicalSocketServer got FD_WRITE_BIT error "
1540 << wsaEvents.iErrorCode[FD_WRITE_BIT];
1541 }
1542 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1543 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
1544 LOG(WARNING) << "PhysicalSocketServer got FD_CONNECT_BIT error "
1545 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
1546 }
1547 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1548 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
1549 LOG(WARNING) << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1550 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
1551 }
1552 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1553 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
1554 LOG(WARNING) << "PhysicalSocketServer got FD_CLOSE_BIT error "
1555 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
1556 }
1557 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001558 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001559 int errcode = 0;
1560 if (wsaEvents.lNetworkEvents & FD_READ)
1561 ff |= DE_READ;
1562 if (wsaEvents.lNetworkEvents & FD_WRITE)
1563 ff |= DE_WRITE;
1564 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1565 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1566 ff |= DE_CONNECT;
1567 } else {
1568 ff |= DE_CLOSE;
1569 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1570 }
1571 }
1572 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1573 ff |= DE_ACCEPT;
1574 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1575 ff |= DE_CLOSE;
1576 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1577 }
1578 if (ff != 0) {
1579 disp->OnPreEvent(ff);
1580 disp->OnEvent(ff, errcode);
1581 }
1582 }
1583 }
nisseede5da42017-01-12 05:15:36 -08001584 RTC_DCHECK(iterators_.back() == &end);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001585 iterators_.pop_back();
nisseede5da42017-01-12 05:15:36 -08001586 RTC_DCHECK(iterators_.back() == &i);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001587 iterators_.pop_back();
1588 }
1589
1590 // Reset the network event until new activity occurs
1591 WSAResetEvent(socket_ev_);
1592 }
1593
1594 // Break?
1595 if (!fWait_)
1596 break;
1597 cmsElapsed = TimeSince(msStart);
1598 if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
1599 break;
1600 }
1601 }
1602
1603 // Done
1604 return true;
1605}
honghaizcec0a082016-01-15 14:49:09 -08001606#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001607
1608} // namespace rtc