blob: bf2f2c64f8ce7ea2d667a3dec178e01c315ef45b [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"
45#include "webrtc/base/common.h"
46#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);
141 VERIFY(0 == getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len));
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000142 udp_ = (SOCK_DGRAM == type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000143 }
jbauch095ae152015-12-18 01:39:55 -0800144}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000145
jbauch095ae152015-12-18 01:39:55 -0800146PhysicalSocket::~PhysicalSocket() {
147 Close();
148}
149
150bool PhysicalSocket::Create(int family, int type) {
151 Close();
152 s_ = ::socket(family, type, 0);
153 udp_ = (SOCK_DGRAM == type);
154 UpdateLastError();
155 if (udp_)
156 enabled_events_ = DE_READ | DE_WRITE;
157 return s_ != INVALID_SOCKET;
158}
159
160SocketAddress PhysicalSocket::GetLocalAddress() const {
161 sockaddr_storage addr_storage = {0};
162 socklen_t addrlen = sizeof(addr_storage);
163 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
164 int result = ::getsockname(s_, addr, &addrlen);
165 SocketAddress address;
166 if (result >= 0) {
167 SocketAddressFromSockAddrStorage(addr_storage, &address);
168 } else {
169 LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
170 << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000171 }
jbauch095ae152015-12-18 01:39:55 -0800172 return address;
173}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000174
jbauch095ae152015-12-18 01:39:55 -0800175SocketAddress PhysicalSocket::GetRemoteAddress() const {
176 sockaddr_storage addr_storage = {0};
177 socklen_t addrlen = sizeof(addr_storage);
178 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
179 int result = ::getpeername(s_, addr, &addrlen);
180 SocketAddress address;
181 if (result >= 0) {
182 SocketAddressFromSockAddrStorage(addr_storage, &address);
183 } else {
184 LOG(LS_WARNING) << "GetRemoteAddress: unable to get remote addr, socket="
185 << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000186 }
jbauch095ae152015-12-18 01:39:55 -0800187 return address;
188}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000189
jbauch095ae152015-12-18 01:39:55 -0800190int PhysicalSocket::Bind(const SocketAddress& bind_addr) {
191 sockaddr_storage addr_storage;
192 size_t len = bind_addr.ToSockAddrStorage(&addr_storage);
193 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
194 int err = ::bind(s_, addr, static_cast<int>(len));
195 UpdateLastError();
tfarinaa41ab932015-10-30 16:08:48 -0700196#if !defined(NDEBUG)
jbauch095ae152015-12-18 01:39:55 -0800197 if (0 == err) {
198 dbg_addr_ = "Bound @ ";
199 dbg_addr_.append(GetLocalAddress().ToString());
200 }
tfarinaa41ab932015-10-30 16:08:48 -0700201#endif
honghaizcec0a082016-01-15 14:49:09 -0800202 if (ss_->network_binder()) {
203 int result =
204 ss_->network_binder()->BindSocketToNetwork(s_, bind_addr.ipaddr());
205 if (result < 0) {
206 LOG(LS_INFO) << "Binding socket to network address "
207 << bind_addr.ipaddr().ToString() << " result " << result;
208 }
209 }
jbauch095ae152015-12-18 01:39:55 -0800210 return err;
211}
212
213int PhysicalSocket::Connect(const SocketAddress& addr) {
214 // TODO(pthatcher): Implicit creation is required to reconnect...
215 // ...but should we make it more explicit?
216 if (state_ != CS_CLOSED) {
217 SetError(EALREADY);
218 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000219 }
jbauch095ae152015-12-18 01:39:55 -0800220 if (addr.IsUnresolvedIP()) {
221 LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
222 resolver_ = new AsyncResolver();
223 resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult);
224 resolver_->Start(addr);
225 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000226 return 0;
227 }
228
jbauch095ae152015-12-18 01:39:55 -0800229 return DoConnect(addr);
230}
231
232int PhysicalSocket::DoConnect(const SocketAddress& connect_addr) {
233 if ((s_ == INVALID_SOCKET) &&
234 !Create(connect_addr.family(), SOCK_STREAM)) {
235 return SOCKET_ERROR;
236 }
237 sockaddr_storage addr_storage;
238 size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
239 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
240 int err = ::connect(s_, addr, static_cast<int>(len));
241 UpdateLastError();
242 if (err == 0) {
243 state_ = CS_CONNECTED;
244 } else if (IsBlockingError(GetError())) {
245 state_ = CS_CONNECTING;
246 enabled_events_ |= DE_CONNECT;
247 } else {
248 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000249 }
250
jbauch095ae152015-12-18 01:39:55 -0800251 enabled_events_ |= DE_READ | DE_WRITE;
252 return 0;
253}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254
jbauch095ae152015-12-18 01:39:55 -0800255int PhysicalSocket::GetError() const {
256 CritScope cs(&crit_);
257 return error_;
258}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000259
jbauch095ae152015-12-18 01:39:55 -0800260void PhysicalSocket::SetError(int error) {
261 CritScope cs(&crit_);
262 error_ = error;
263}
264
265AsyncSocket::ConnState PhysicalSocket::GetState() const {
266 return state_;
267}
268
269int PhysicalSocket::GetOption(Option opt, int* value) {
270 int slevel;
271 int sopt;
272 if (TranslateOption(opt, &slevel, &sopt) == -1)
273 return -1;
274 socklen_t optlen = sizeof(*value);
275 int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
276 if (ret != -1 && opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000277#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800278 *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000279#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000280 }
jbauch095ae152015-12-18 01:39:55 -0800281 return ret;
282}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000283
jbauch095ae152015-12-18 01:39:55 -0800284int PhysicalSocket::SetOption(Option opt, int value) {
285 int slevel;
286 int sopt;
287 if (TranslateOption(opt, &slevel, &sopt) == -1)
288 return -1;
289 if (opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000290#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800291 value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000292#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000293 }
jbauch095ae152015-12-18 01:39:55 -0800294 return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
295}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000296
jbauch095ae152015-12-18 01:39:55 -0800297int PhysicalSocket::Send(const void* pv, size_t cb) {
jbauchf2a2bf42016-02-03 16:45:32 -0800298 int sent = DoSend(s_, reinterpret_cast<const char *>(pv),
299 static_cast<int>(cb),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000300#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800301 // Suppress SIGPIPE. Without this, attempting to send on a socket whose
302 // other end is closed will result in a SIGPIPE signal being raised to
303 // our process, which by default will terminate the process, which we
304 // don't want. By specifying this flag, we'll just get the error EPIPE
305 // instead and can handle the error gracefully.
306 MSG_NOSIGNAL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000307#else
jbauch095ae152015-12-18 01:39:55 -0800308 0
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000309#endif
jbauch095ae152015-12-18 01:39:55 -0800310 );
311 UpdateLastError();
312 MaybeRemapSendError();
313 // We have seen minidumps where this may be false.
314 ASSERT(sent <= static_cast<int>(cb));
jbauchf2a2bf42016-02-03 16:45:32 -0800315 if ((sent > 0 && sent < static_cast<int>(cb)) ||
316 (sent < 0 && IsBlockingError(GetError()))) {
jbauch095ae152015-12-18 01:39:55 -0800317 enabled_events_ |= DE_WRITE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000318 }
jbauch095ae152015-12-18 01:39:55 -0800319 return sent;
320}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000321
jbauch095ae152015-12-18 01:39:55 -0800322int PhysicalSocket::SendTo(const void* buffer,
323 size_t length,
324 const SocketAddress& addr) {
325 sockaddr_storage saddr;
326 size_t len = addr.ToSockAddrStorage(&saddr);
jbauchf2a2bf42016-02-03 16:45:32 -0800327 int sent = DoSendTo(
jbauch095ae152015-12-18 01:39:55 -0800328 s_, static_cast<const char *>(buffer), static_cast<int>(length),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000329#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800330 // Suppress SIGPIPE. See above for explanation.
331 MSG_NOSIGNAL,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000332#else
jbauch095ae152015-12-18 01:39:55 -0800333 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000334#endif
jbauch095ae152015-12-18 01:39:55 -0800335 reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
336 UpdateLastError();
337 MaybeRemapSendError();
338 // We have seen minidumps where this may be false.
339 ASSERT(sent <= static_cast<int>(length));
jbauchf2a2bf42016-02-03 16:45:32 -0800340 if ((sent > 0 && sent < static_cast<int>(length)) ||
341 (sent < 0 && IsBlockingError(GetError()))) {
jbauch095ae152015-12-18 01:39:55 -0800342 enabled_events_ |= DE_WRITE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000343 }
jbauch095ae152015-12-18 01:39:55 -0800344 return sent;
345}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000346
Stefan Holmer9131efd2016-05-23 18:19:26 +0200347int PhysicalSocket::Recv(void* buffer, size_t length, int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800348 int received = ::recv(s_, static_cast<char*>(buffer),
349 static_cast<int>(length), 0);
350 if ((received == 0) && (length != 0)) {
351 // Note: on graceful shutdown, recv can return 0. In this case, we
352 // pretend it is blocking, and then signal close, so that simplifying
353 // assumptions can be made about Recv.
354 LOG(LS_WARNING) << "EOF from socket; deferring close event";
355 // Must turn this back on so that the select() loop will notice the close
356 // event.
357 enabled_events_ |= DE_READ;
358 SetError(EWOULDBLOCK);
359 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000360 }
Stefan Holmer9131efd2016-05-23 18:19:26 +0200361 if (timestamp) {
362 *timestamp = GetSocketRecvTimestamp(s_);
363 }
jbauch095ae152015-12-18 01:39:55 -0800364 UpdateLastError();
365 int error = GetError();
366 bool success = (received >= 0) || IsBlockingError(error);
367 if (udp_ || success) {
368 enabled_events_ |= DE_READ;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000369 }
jbauch095ae152015-12-18 01:39:55 -0800370 if (!success) {
371 LOG_F(LS_VERBOSE) << "Error = " << error;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000372 }
jbauch095ae152015-12-18 01:39:55 -0800373 return received;
374}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000375
jbauch095ae152015-12-18 01:39:55 -0800376int PhysicalSocket::RecvFrom(void* buffer,
377 size_t length,
Stefan Holmer9131efd2016-05-23 18:19:26 +0200378 SocketAddress* out_addr,
379 int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800380 sockaddr_storage addr_storage;
381 socklen_t addr_len = sizeof(addr_storage);
382 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
383 int received = ::recvfrom(s_, static_cast<char*>(buffer),
384 static_cast<int>(length), 0, addr, &addr_len);
Stefan Holmer9131efd2016-05-23 18:19:26 +0200385 if (timestamp) {
386 *timestamp = GetSocketRecvTimestamp(s_);
387 }
jbauch095ae152015-12-18 01:39:55 -0800388 UpdateLastError();
389 if ((received >= 0) && (out_addr != nullptr))
390 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
391 int error = GetError();
392 bool success = (received >= 0) || IsBlockingError(error);
393 if (udp_ || success) {
394 enabled_events_ |= DE_READ;
395 }
396 if (!success) {
397 LOG_F(LS_VERBOSE) << "Error = " << error;
398 }
399 return received;
400}
401
402int PhysicalSocket::Listen(int backlog) {
403 int err = ::listen(s_, backlog);
404 UpdateLastError();
405 if (err == 0) {
406 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000407 enabled_events_ |= DE_ACCEPT;
jbauch095ae152015-12-18 01:39:55 -0800408#if !defined(NDEBUG)
409 dbg_addr_ = "Listening @ ";
410 dbg_addr_.append(GetLocalAddress().ToString());
411#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000412 }
jbauch095ae152015-12-18 01:39:55 -0800413 return err;
414}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000415
jbauch095ae152015-12-18 01:39:55 -0800416AsyncSocket* PhysicalSocket::Accept(SocketAddress* out_addr) {
417 // Always re-subscribe DE_ACCEPT to make sure new incoming connections will
418 // trigger an event even if DoAccept returns an error here.
419 enabled_events_ |= DE_ACCEPT;
420 sockaddr_storage addr_storage;
421 socklen_t addr_len = sizeof(addr_storage);
422 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
423 SOCKET s = DoAccept(s_, addr, &addr_len);
424 UpdateLastError();
425 if (s == INVALID_SOCKET)
426 return nullptr;
427 if (out_addr != nullptr)
428 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
429 return ss_->WrapSocket(s);
430}
431
432int PhysicalSocket::Close() {
433 if (s_ == INVALID_SOCKET)
434 return 0;
435 int err = ::closesocket(s_);
436 UpdateLastError();
437 s_ = INVALID_SOCKET;
438 state_ = CS_CLOSED;
439 enabled_events_ = 0;
440 if (resolver_) {
441 resolver_->Destroy(false);
442 resolver_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000443 }
jbauch095ae152015-12-18 01:39:55 -0800444 return err;
445}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000446
jbauch095ae152015-12-18 01:39:55 -0800447int PhysicalSocket::EstimateMTU(uint16_t* mtu) {
448 SocketAddress addr = GetRemoteAddress();
449 if (addr.IsAnyIP()) {
450 SetError(ENOTCONN);
451 return -1;
452 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000453
454#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800455 // Gets the interface MTU (TTL=1) for the interface used to reach |addr|.
456 WinPing ping;
457 if (!ping.IsValid()) {
458 SetError(EINVAL); // can't think of a better error ID
459 return -1;
460 }
461 int header_size = ICMP_HEADER_SIZE;
462 if (addr.family() == AF_INET6) {
463 header_size += IPV6_HEADER_SIZE;
464 } else if (addr.family() == AF_INET) {
465 header_size += IP_HEADER_SIZE;
466 }
467
468 for (int level = 0; PACKET_MAXIMUMS[level + 1] > 0; ++level) {
469 int32_t size = PACKET_MAXIMUMS[level] - header_size;
470 WinPing::PingResult result = ping.Ping(addr.ipaddr(), size,
471 ICMP_PING_TIMEOUT_MILLIS,
472 1, false);
473 if (result == WinPing::PING_FAIL) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000474 SetError(EINVAL); // can't think of a better error ID
475 return -1;
jbauch095ae152015-12-18 01:39:55 -0800476 } else if (result != WinPing::PING_TOO_LARGE) {
477 *mtu = PACKET_MAXIMUMS[level];
478 return 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000479 }
jbauch095ae152015-12-18 01:39:55 -0800480 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000481
jbauch095ae152015-12-18 01:39:55 -0800482 ASSERT(false);
483 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000484#elif defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800485 // No simple way to do this on Mac OS X.
486 // SIOCGIFMTU would work if we knew which interface would be used, but
487 // figuring that out is pretty complicated. For now we'll return an error
488 // and let the caller pick a default MTU.
489 SetError(EINVAL);
490 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000491#elif defined(WEBRTC_LINUX)
jbauch095ae152015-12-18 01:39:55 -0800492 // Gets the path MTU.
493 int value;
494 socklen_t vlen = sizeof(value);
495 int err = getsockopt(s_, IPPROTO_IP, IP_MTU, &value, &vlen);
496 if (err < 0) {
497 UpdateLastError();
498 return err;
499 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000500
jbauch095ae152015-12-18 01:39:55 -0800501 ASSERT((0 <= value) && (value <= 65536));
502 *mtu = value;
503 return 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000504#elif defined(__native_client__)
jbauch095ae152015-12-18 01:39:55 -0800505 // Most socket operations, including this, will fail in NaCl's sandbox.
506 error_ = EACCES;
507 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000508#endif
jbauch095ae152015-12-18 01:39:55 -0800509}
510
jbauch095ae152015-12-18 01:39:55 -0800511SOCKET PhysicalSocket::DoAccept(SOCKET socket,
512 sockaddr* addr,
513 socklen_t* addrlen) {
514 return ::accept(socket, addr, addrlen);
515}
516
jbauchf2a2bf42016-02-03 16:45:32 -0800517int PhysicalSocket::DoSend(SOCKET socket, const char* buf, int len, int flags) {
518 return ::send(socket, buf, len, flags);
519}
520
521int PhysicalSocket::DoSendTo(SOCKET socket,
522 const char* buf,
523 int len,
524 int flags,
525 const struct sockaddr* dest_addr,
526 socklen_t addrlen) {
527 return ::sendto(socket, buf, len, flags, dest_addr, addrlen);
528}
529
jbauch095ae152015-12-18 01:39:55 -0800530void PhysicalSocket::OnResolveResult(AsyncResolverInterface* resolver) {
531 if (resolver != resolver_) {
532 return;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000533 }
534
jbauch095ae152015-12-18 01:39:55 -0800535 int error = resolver_->GetError();
536 if (error == 0) {
537 error = DoConnect(resolver_->address());
538 } else {
539 Close();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000540 }
541
jbauch095ae152015-12-18 01:39:55 -0800542 if (error) {
543 SetError(error);
544 SignalCloseEvent(this, error);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000545 }
jbauch095ae152015-12-18 01:39:55 -0800546}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000547
jbauch095ae152015-12-18 01:39:55 -0800548void PhysicalSocket::UpdateLastError() {
549 SetError(LAST_SYSTEM_ERROR);
550}
551
552void PhysicalSocket::MaybeRemapSendError() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000553#if defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800554 // https://developer.apple.com/library/mac/documentation/Darwin/
555 // Reference/ManPages/man2/sendto.2.html
556 // ENOBUFS - The output queue for a network interface is full.
557 // This generally indicates that the interface has stopped sending,
558 // but may be caused by transient congestion.
559 if (GetError() == ENOBUFS) {
560 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000561 }
jbauch095ae152015-12-18 01:39:55 -0800562#endif
563}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000564
jbauch095ae152015-12-18 01:39:55 -0800565int PhysicalSocket::TranslateOption(Option opt, int* slevel, int* sopt) {
566 switch (opt) {
567 case OPT_DONTFRAGMENT:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000568#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800569 *slevel = IPPROTO_IP;
570 *sopt = IP_DONTFRAGMENT;
571 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000572#elif defined(WEBRTC_MAC) || defined(BSD) || defined(__native_client__)
jbauch095ae152015-12-18 01:39:55 -0800573 LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
574 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000575#elif defined(WEBRTC_POSIX)
jbauch095ae152015-12-18 01:39:55 -0800576 *slevel = IPPROTO_IP;
577 *sopt = IP_MTU_DISCOVER;
578 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000579#endif
jbauch095ae152015-12-18 01:39:55 -0800580 case OPT_RCVBUF:
581 *slevel = SOL_SOCKET;
582 *sopt = SO_RCVBUF;
583 break;
584 case OPT_SNDBUF:
585 *slevel = SOL_SOCKET;
586 *sopt = SO_SNDBUF;
587 break;
588 case OPT_NODELAY:
589 *slevel = IPPROTO_TCP;
590 *sopt = TCP_NODELAY;
591 break;
592 case OPT_DSCP:
593 LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
594 return -1;
595 case OPT_RTP_SENDTIME_EXTN_ID:
596 return -1; // No logging is necessary as this not a OS socket option.
597 default:
598 ASSERT(false);
599 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000600 }
jbauch095ae152015-12-18 01:39:55 -0800601 return 0;
602}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000603
jbauch4331fcd2016-01-06 22:20:28 -0800604SocketDispatcher::SocketDispatcher(PhysicalSocketServer *ss)
605#if defined(WEBRTC_WIN)
606 : PhysicalSocket(ss), id_(0), signal_close_(false)
607#else
608 : PhysicalSocket(ss)
609#endif
610{
611}
612
613SocketDispatcher::SocketDispatcher(SOCKET s, PhysicalSocketServer *ss)
614#if defined(WEBRTC_WIN)
615 : PhysicalSocket(ss, s), id_(0), signal_close_(false)
616#else
617 : PhysicalSocket(ss, s)
618#endif
619{
620}
621
622SocketDispatcher::~SocketDispatcher() {
623 Close();
624}
625
626bool SocketDispatcher::Initialize() {
627 ASSERT(s_ != INVALID_SOCKET);
628 // Must be a non-blocking
629#if defined(WEBRTC_WIN)
630 u_long argp = 1;
631 ioctlsocket(s_, FIONBIO, &argp);
632#elif defined(WEBRTC_POSIX)
633 fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
634#endif
635 ss_->Add(this);
636 return true;
637}
638
639bool SocketDispatcher::Create(int type) {
640 return Create(AF_INET, type);
641}
642
643bool SocketDispatcher::Create(int family, int type) {
644 // Change the socket to be non-blocking.
645 if (!PhysicalSocket::Create(family, type))
646 return false;
647
648 if (!Initialize())
649 return false;
650
651#if defined(WEBRTC_WIN)
652 do { id_ = ++next_id_; } while (id_ == 0);
653#endif
654 return true;
655}
656
657#if defined(WEBRTC_WIN)
658
659WSAEVENT SocketDispatcher::GetWSAEvent() {
660 return WSA_INVALID_EVENT;
661}
662
663SOCKET SocketDispatcher::GetSocket() {
664 return s_;
665}
666
667bool SocketDispatcher::CheckSignalClose() {
668 if (!signal_close_)
669 return false;
670
671 char ch;
672 if (recv(s_, &ch, 1, MSG_PEEK) > 0)
673 return false;
674
675 state_ = CS_CLOSED;
676 signal_close_ = false;
677 SignalCloseEvent(this, signal_err_);
678 return true;
679}
680
681int SocketDispatcher::next_id_ = 0;
682
683#elif defined(WEBRTC_POSIX)
684
685int SocketDispatcher::GetDescriptor() {
686 return s_;
687}
688
689bool SocketDispatcher::IsDescriptorClosed() {
690 // We don't have a reliable way of distinguishing end-of-stream
691 // from readability. So test on each readable call. Is this
692 // inefficient? Probably.
693 char ch;
694 ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
695 if (res > 0) {
696 // Data available, so not closed.
697 return false;
698 } else if (res == 0) {
699 // EOF, so closed.
700 return true;
701 } else { // error
702 switch (errno) {
703 // Returned if we've already closed s_.
704 case EBADF:
705 // Returned during ungraceful peer shutdown.
706 case ECONNRESET:
707 return true;
708 default:
709 // Assume that all other errors are just blocking errors, meaning the
710 // connection is still good but we just can't read from it right now.
711 // This should only happen when connecting (and at most once), because
712 // in all other cases this function is only called if the file
713 // descriptor is already known to be in the readable state. However,
714 // it's not necessary a problem if we spuriously interpret a
715 // "connection lost"-type error as a blocking error, because typically
716 // the next recv() will get EOF, so we'll still eventually notice that
717 // the socket is closed.
718 LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
719 return false;
720 }
721 }
722}
723
724#endif // WEBRTC_POSIX
725
726uint32_t SocketDispatcher::GetRequestedEvents() {
727 return enabled_events_;
728}
729
730void SocketDispatcher::OnPreEvent(uint32_t ff) {
731 if ((ff & DE_CONNECT) != 0)
732 state_ = CS_CONNECTED;
733
734#if defined(WEBRTC_WIN)
735 // We set CS_CLOSED from CheckSignalClose.
736#elif defined(WEBRTC_POSIX)
737 if ((ff & DE_CLOSE) != 0)
738 state_ = CS_CLOSED;
739#endif
740}
741
742#if defined(WEBRTC_WIN)
743
744void SocketDispatcher::OnEvent(uint32_t ff, int err) {
745 int cache_id = id_;
746 // Make sure we deliver connect/accept first. Otherwise, consumers may see
747 // something like a READ followed by a CONNECT, which would be odd.
748 if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
749 if (ff != DE_CONNECT)
750 LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
751 enabled_events_ &= ~DE_CONNECT;
752#if !defined(NDEBUG)
753 dbg_addr_ = "Connected @ ";
754 dbg_addr_.append(GetRemoteAddress().ToString());
755#endif
756 SignalConnectEvent(this);
757 }
758 if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
759 enabled_events_ &= ~DE_ACCEPT;
760 SignalReadEvent(this);
761 }
762 if ((ff & DE_READ) != 0) {
763 enabled_events_ &= ~DE_READ;
764 SignalReadEvent(this);
765 }
766 if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
767 enabled_events_ &= ~DE_WRITE;
768 SignalWriteEvent(this);
769 }
770 if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
771 signal_close_ = true;
772 signal_err_ = err;
773 }
774}
775
776#elif defined(WEBRTC_POSIX)
777
778void SocketDispatcher::OnEvent(uint32_t ff, int err) {
779 // Make sure we deliver connect/accept first. Otherwise, consumers may see
780 // something like a READ followed by a CONNECT, which would be odd.
781 if ((ff & DE_CONNECT) != 0) {
782 enabled_events_ &= ~DE_CONNECT;
783 SignalConnectEvent(this);
784 }
785 if ((ff & DE_ACCEPT) != 0) {
786 enabled_events_ &= ~DE_ACCEPT;
787 SignalReadEvent(this);
788 }
789 if ((ff & DE_READ) != 0) {
790 enabled_events_ &= ~DE_READ;
791 SignalReadEvent(this);
792 }
793 if ((ff & DE_WRITE) != 0) {
794 enabled_events_ &= ~DE_WRITE;
795 SignalWriteEvent(this);
796 }
797 if ((ff & DE_CLOSE) != 0) {
798 // The socket is now dead to us, so stop checking it.
799 enabled_events_ = 0;
800 SignalCloseEvent(this, err);
801 }
802}
803
804#endif // WEBRTC_POSIX
805
806int SocketDispatcher::Close() {
807 if (s_ == INVALID_SOCKET)
808 return 0;
809
810#if defined(WEBRTC_WIN)
811 id_ = 0;
812 signal_close_ = false;
813#endif
814 ss_->Remove(this);
815 return PhysicalSocket::Close();
816}
817
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000818#if defined(WEBRTC_POSIX)
819class EventDispatcher : public Dispatcher {
820 public:
821 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
822 if (pipe(afd_) < 0)
823 LOG(LERROR) << "pipe failed";
824 ss_->Add(this);
825 }
826
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000827 ~EventDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000828 ss_->Remove(this);
829 close(afd_[0]);
830 close(afd_[1]);
831 }
832
833 virtual void Signal() {
834 CritScope cs(&crit_);
835 if (!fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200836 const uint8_t b[1] = {0};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000837 if (VERIFY(1 == write(afd_[1], b, sizeof(b)))) {
838 fSignaled_ = true;
839 }
840 }
841 }
842
Peter Boström0c4e06b2015-10-07 12:23:21 +0200843 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000844
Peter Boström0c4e06b2015-10-07 12:23:21 +0200845 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000846 // It is not possible to perfectly emulate an auto-resetting event with
847 // pipes. This simulates it by resetting before the event is handled.
848
849 CritScope cs(&crit_);
850 if (fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200851 uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000852 VERIFY(1 == read(afd_[0], b, sizeof(b)));
853 fSignaled_ = false;
854 }
855 }
856
Peter Boström0c4e06b2015-10-07 12:23:21 +0200857 void OnEvent(uint32_t ff, int err) override { ASSERT(false); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000858
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000859 int GetDescriptor() override { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000860
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000861 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000862
863 private:
864 PhysicalSocketServer *ss_;
865 int afd_[2];
866 bool fSignaled_;
867 CriticalSection crit_;
868};
869
870// These two classes use the self-pipe trick to deliver POSIX signals to our
871// select loop. This is the only safe, reliable, cross-platform way to do
872// non-trivial things with a POSIX signal in an event-driven program (until
873// proper pselect() implementations become ubiquitous).
874
875class PosixSignalHandler {
876 public:
877 // POSIX only specifies 32 signals, but in principle the system might have
878 // more and the programmer might choose to use them, so we size our array
879 // for 128.
880 static const int kNumPosixSignals = 128;
881
882 // There is just a single global instance. (Signal handlers do not get any
883 // sort of user-defined void * parameter, so they can't access anything that
884 // isn't global.)
885 static PosixSignalHandler* Instance() {
Andrew MacDonald469c2c02015-05-22 17:50:26 -0700886 RTC_DEFINE_STATIC_LOCAL(PosixSignalHandler, instance, ());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000887 return &instance;
888 }
889
890 // Returns true if the given signal number is set.
891 bool IsSignalSet(int signum) const {
tfarina5237aaf2015-11-10 23:44:30 -0800892 ASSERT(signum < static_cast<int>(arraysize(received_signal_)));
893 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000894 return received_signal_[signum];
895 } else {
896 return false;
897 }
898 }
899
900 // Clears the given signal number.
901 void ClearSignal(int signum) {
tfarina5237aaf2015-11-10 23:44:30 -0800902 ASSERT(signum < static_cast<int>(arraysize(received_signal_)));
903 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000904 received_signal_[signum] = false;
905 }
906 }
907
908 // Returns the file descriptor to monitor for signal events.
909 int GetDescriptor() const {
910 return afd_[0];
911 }
912
913 // This is called directly from our real signal handler, so it must be
914 // signal-handler-safe. That means it cannot assume anything about the
915 // user-level state of the process, since the handler could be executed at any
916 // time on any thread.
917 void OnPosixSignalReceived(int signum) {
tfarina5237aaf2015-11-10 23:44:30 -0800918 if (signum >= static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000919 // We don't have space in our array for this.
920 return;
921 }
922 // Set a flag saying we've seen this signal.
923 received_signal_[signum] = true;
924 // Notify application code that we got a signal.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200925 const uint8_t b[1] = {0};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000926 if (-1 == write(afd_[1], b, sizeof(b))) {
927 // Nothing we can do here. If there's an error somehow then there's
928 // nothing we can safely do from a signal handler.
929 // No, we can't even safely log it.
930 // But, we still have to check the return value here. Otherwise,
931 // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
932 return;
933 }
934 }
935
936 private:
937 PosixSignalHandler() {
938 if (pipe(afd_) < 0) {
939 LOG_ERR(LS_ERROR) << "pipe failed";
940 return;
941 }
942 if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
943 LOG_ERR(LS_WARNING) << "fcntl #1 failed";
944 }
945 if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
946 LOG_ERR(LS_WARNING) << "fcntl #2 failed";
947 }
948 memset(const_cast<void *>(static_cast<volatile void *>(received_signal_)),
949 0,
950 sizeof(received_signal_));
951 }
952
953 ~PosixSignalHandler() {
954 int fd1 = afd_[0];
955 int fd2 = afd_[1];
956 // We clobber the stored file descriptor numbers here or else in principle
957 // a signal that happens to be delivered during application termination
958 // could erroneously write a zero byte to an unrelated file handle in
959 // OnPosixSignalReceived() if some other file happens to be opened later
960 // during shutdown and happens to be given the same file descriptor number
961 // as our pipe had. Unfortunately even with this precaution there is still a
962 // race where that could occur if said signal happens to be handled
963 // concurrently with this code and happens to have already read the value of
964 // afd_[1] from memory before we clobber it, but that's unlikely.
965 afd_[0] = -1;
966 afd_[1] = -1;
967 close(fd1);
968 close(fd2);
969 }
970
971 int afd_[2];
972 // These are boolean flags that will be set in our signal handler and read
973 // and cleared from Wait(). There is a race involved in this, but it is
974 // benign. The signal handler sets the flag before signaling the pipe, so
975 // we'll never end up blocking in select() while a flag is still true.
976 // However, if two of the same signal arrive close to each other then it's
977 // possible that the second time the handler may set the flag while it's still
978 // true, meaning that signal will be missed. But the first occurrence of it
979 // will still be handled, so this isn't a problem.
980 // Volatile is not necessary here for correctness, but this data _is_ volatile
981 // so I've marked it as such.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200982 volatile uint8_t received_signal_[kNumPosixSignals];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000983};
984
985class PosixSignalDispatcher : public Dispatcher {
986 public:
987 PosixSignalDispatcher(PhysicalSocketServer *owner) : owner_(owner) {
988 owner_->Add(this);
989 }
990
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000991 ~PosixSignalDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000992 owner_->Remove(this);
993 }
994
Peter Boström0c4e06b2015-10-07 12:23:21 +0200995 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000996
Peter Boström0c4e06b2015-10-07 12:23:21 +0200997 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000998 // Events might get grouped if signals come very fast, so we read out up to
999 // 16 bytes to make sure we keep the pipe empty.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001000 uint8_t b[16];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001001 ssize_t ret = read(GetDescriptor(), b, sizeof(b));
1002 if (ret < 0) {
1003 LOG_ERR(LS_WARNING) << "Error in read()";
1004 } else if (ret == 0) {
1005 LOG(LS_WARNING) << "Should have read at least one byte";
1006 }
1007 }
1008
Peter Boström0c4e06b2015-10-07 12:23:21 +02001009 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001010 for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
1011 ++signum) {
1012 if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
1013 PosixSignalHandler::Instance()->ClearSignal(signum);
1014 HandlerMap::iterator i = handlers_.find(signum);
1015 if (i == handlers_.end()) {
1016 // This can happen if a signal is delivered to our process at around
1017 // the same time as we unset our handler for it. It is not an error
1018 // condition, but it's unusual enough to be worth logging.
1019 LOG(LS_INFO) << "Received signal with no handler: " << signum;
1020 } else {
1021 // Otherwise, execute our handler.
1022 (*i->second)(signum);
1023 }
1024 }
1025 }
1026 }
1027
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001028 int GetDescriptor() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001029 return PosixSignalHandler::Instance()->GetDescriptor();
1030 }
1031
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001032 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001033
1034 void SetHandler(int signum, void (*handler)(int)) {
1035 handlers_[signum] = handler;
1036 }
1037
1038 void ClearHandler(int signum) {
1039 handlers_.erase(signum);
1040 }
1041
1042 bool HasHandlers() {
1043 return !handlers_.empty();
1044 }
1045
1046 private:
1047 typedef std::map<int, void (*)(int)> HandlerMap;
1048
1049 HandlerMap handlers_;
1050 // Our owner.
1051 PhysicalSocketServer *owner_;
1052};
1053
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001054#endif // WEBRTC_POSIX
1055
1056#if defined(WEBRTC_WIN)
Peter Boström0c4e06b2015-10-07 12:23:21 +02001057static uint32_t FlagsToEvents(uint32_t events) {
1058 uint32_t ffFD = FD_CLOSE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001059 if (events & DE_READ)
1060 ffFD |= FD_READ;
1061 if (events & DE_WRITE)
1062 ffFD |= FD_WRITE;
1063 if (events & DE_CONNECT)
1064 ffFD |= FD_CONNECT;
1065 if (events & DE_ACCEPT)
1066 ffFD |= FD_ACCEPT;
1067 return ffFD;
1068}
1069
1070class EventDispatcher : public Dispatcher {
1071 public:
1072 EventDispatcher(PhysicalSocketServer *ss) : ss_(ss) {
1073 hev_ = WSACreateEvent();
1074 if (hev_) {
1075 ss_->Add(this);
1076 }
1077 }
1078
1079 ~EventDispatcher() {
1080 if (hev_ != NULL) {
1081 ss_->Remove(this);
1082 WSACloseEvent(hev_);
1083 hev_ = NULL;
1084 }
1085 }
1086
1087 virtual void Signal() {
1088 if (hev_ != NULL)
1089 WSASetEvent(hev_);
1090 }
1091
Peter Boström0c4e06b2015-10-07 12:23:21 +02001092 virtual uint32_t GetRequestedEvents() { return 0; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001093
Peter Boström0c4e06b2015-10-07 12:23:21 +02001094 virtual void OnPreEvent(uint32_t ff) { WSAResetEvent(hev_); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001095
Peter Boström0c4e06b2015-10-07 12:23:21 +02001096 virtual void OnEvent(uint32_t ff, int err) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001097
1098 virtual WSAEVENT GetWSAEvent() {
1099 return hev_;
1100 }
1101
1102 virtual SOCKET GetSocket() {
1103 return INVALID_SOCKET;
1104 }
1105
1106 virtual bool CheckSignalClose() { return false; }
1107
1108private:
1109 PhysicalSocketServer* ss_;
1110 WSAEVENT hev_;
1111};
honghaizcec0a082016-01-15 14:49:09 -08001112#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001113
1114// Sets the value of a boolean value to false when signaled.
1115class Signaler : public EventDispatcher {
1116 public:
1117 Signaler(PhysicalSocketServer* ss, bool* pf)
1118 : EventDispatcher(ss), pf_(pf) {
1119 }
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001120 ~Signaler() override { }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001121
Peter Boström0c4e06b2015-10-07 12:23:21 +02001122 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001123 if (pf_)
1124 *pf_ = false;
1125 }
1126
1127 private:
1128 bool *pf_;
1129};
1130
1131PhysicalSocketServer::PhysicalSocketServer()
1132 : fWait_(false) {
1133 signal_wakeup_ = new Signaler(this, &fWait_);
1134#if defined(WEBRTC_WIN)
1135 socket_ev_ = WSACreateEvent();
1136#endif
1137}
1138
1139PhysicalSocketServer::~PhysicalSocketServer() {
1140#if defined(WEBRTC_WIN)
1141 WSACloseEvent(socket_ev_);
1142#endif
1143#if defined(WEBRTC_POSIX)
1144 signal_dispatcher_.reset();
1145#endif
1146 delete signal_wakeup_;
1147 ASSERT(dispatchers_.empty());
1148}
1149
1150void PhysicalSocketServer::WakeUp() {
1151 signal_wakeup_->Signal();
1152}
1153
1154Socket* PhysicalSocketServer::CreateSocket(int type) {
1155 return CreateSocket(AF_INET, type);
1156}
1157
1158Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
1159 PhysicalSocket* socket = new PhysicalSocket(this);
1160 if (socket->Create(family, type)) {
1161 return socket;
1162 } else {
1163 delete socket;
jbauch095ae152015-12-18 01:39:55 -08001164 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001165 }
1166}
1167
1168AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int type) {
1169 return CreateAsyncSocket(AF_INET, type);
1170}
1171
1172AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
1173 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1174 if (dispatcher->Create(family, type)) {
1175 return dispatcher;
1176 } else {
1177 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001178 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001179 }
1180}
1181
1182AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
1183 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1184 if (dispatcher->Initialize()) {
1185 return dispatcher;
1186 } else {
1187 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001188 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001189 }
1190}
1191
1192void PhysicalSocketServer::Add(Dispatcher *pdispatcher) {
1193 CritScope cs(&crit_);
1194 // Prevent duplicates. This can cause dead dispatchers to stick around.
1195 DispatcherList::iterator pos = std::find(dispatchers_.begin(),
1196 dispatchers_.end(),
1197 pdispatcher);
1198 if (pos != dispatchers_.end())
1199 return;
1200 dispatchers_.push_back(pdispatcher);
1201}
1202
1203void PhysicalSocketServer::Remove(Dispatcher *pdispatcher) {
1204 CritScope cs(&crit_);
1205 DispatcherList::iterator pos = std::find(dispatchers_.begin(),
1206 dispatchers_.end(),
1207 pdispatcher);
1208 // We silently ignore duplicate calls to Add, so we should silently ignore
1209 // the (expected) symmetric calls to Remove. Note that this may still hide
1210 // a real issue, so we at least log a warning about it.
1211 if (pos == dispatchers_.end()) {
1212 LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
1213 << "dispatcher, potentially from a duplicate call to Add.";
1214 return;
1215 }
1216 size_t index = pos - dispatchers_.begin();
1217 dispatchers_.erase(pos);
1218 for (IteratorList::iterator it = iterators_.begin(); it != iterators_.end();
1219 ++it) {
1220 if (index < **it) {
1221 --**it;
1222 }
1223 }
1224}
1225
1226#if defined(WEBRTC_POSIX)
1227bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
1228 // Calculate timing information
1229
1230 struct timeval *ptvWait = NULL;
1231 struct timeval tvWait;
1232 struct timeval tvStop;
1233 if (cmsWait != kForever) {
1234 // Calculate wait timeval
1235 tvWait.tv_sec = cmsWait / 1000;
1236 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1237 ptvWait = &tvWait;
1238
1239 // Calculate when to return in a timeval
1240 gettimeofday(&tvStop, NULL);
1241 tvStop.tv_sec += tvWait.tv_sec;
1242 tvStop.tv_usec += tvWait.tv_usec;
1243 if (tvStop.tv_usec >= 1000000) {
1244 tvStop.tv_usec -= 1000000;
1245 tvStop.tv_sec += 1;
1246 }
1247 }
1248
1249 // Zero all fd_sets. Don't need to do this inside the loop since
1250 // select() zeros the descriptors not signaled
1251
1252 fd_set fdsRead;
1253 FD_ZERO(&fdsRead);
1254 fd_set fdsWrite;
1255 FD_ZERO(&fdsWrite);
pbos@webrtc.org27e58982014-10-07 17:56:53 +00001256 // Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1257 // inline assembly in FD_ZERO.
1258 // http://crbug.com/344505
1259#ifdef MEMORY_SANITIZER
1260 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1261 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1262#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001263
1264 fWait_ = true;
1265
1266 while (fWait_) {
1267 int fdmax = -1;
1268 {
1269 CritScope cr(&crit_);
1270 for (size_t i = 0; i < dispatchers_.size(); ++i) {
1271 // Query dispatchers for read and write wait state
1272 Dispatcher *pdispatcher = dispatchers_[i];
1273 ASSERT(pdispatcher);
1274 if (!process_io && (pdispatcher != signal_wakeup_))
1275 continue;
1276 int fd = pdispatcher->GetDescriptor();
1277 if (fd > fdmax)
1278 fdmax = fd;
1279
Peter Boström0c4e06b2015-10-07 12:23:21 +02001280 uint32_t ff = pdispatcher->GetRequestedEvents();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001281 if (ff & (DE_READ | DE_ACCEPT))
1282 FD_SET(fd, &fdsRead);
1283 if (ff & (DE_WRITE | DE_CONNECT))
1284 FD_SET(fd, &fdsWrite);
1285 }
1286 }
1287
1288 // Wait then call handlers as appropriate
1289 // < 0 means error
1290 // 0 means timeout
1291 // > 0 means count of descriptors ready
1292 int n = select(fdmax + 1, &fdsRead, &fdsWrite, NULL, ptvWait);
1293
1294 // If error, return error.
1295 if (n < 0) {
1296 if (errno != EINTR) {
1297 LOG_E(LS_ERROR, EN, errno) << "select";
1298 return false;
1299 }
1300 // Else ignore the error and keep going. If this EINTR was for one of the
1301 // signals managed by this PhysicalSocketServer, the
1302 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1303 // iteration.
1304 } else if (n == 0) {
1305 // If timeout, return success
1306 return true;
1307 } else {
1308 // We have signaled descriptors
1309 CritScope cr(&crit_);
1310 for (size_t i = 0; i < dispatchers_.size(); ++i) {
1311 Dispatcher *pdispatcher = dispatchers_[i];
1312 int fd = pdispatcher->GetDescriptor();
Peter Boström0c4e06b2015-10-07 12:23:21 +02001313 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001314 int errcode = 0;
1315
1316 // Reap any error code, which can be signaled through reads or writes.
jbauch095ae152015-12-18 01:39:55 -08001317 // TODO(pthatcher): Should we set errcode if getsockopt fails?
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001318 if (FD_ISSET(fd, &fdsRead) || FD_ISSET(fd, &fdsWrite)) {
1319 socklen_t len = sizeof(errcode);
1320 ::getsockopt(fd, SOL_SOCKET, SO_ERROR, &errcode, &len);
1321 }
1322
1323 // Check readable descriptors. If we're waiting on an accept, signal
1324 // that. Otherwise we're waiting for data, check to see if we're
1325 // readable or really closed.
jbauch095ae152015-12-18 01:39:55 -08001326 // TODO(pthatcher): Only peek at TCP descriptors.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001327 if (FD_ISSET(fd, &fdsRead)) {
1328 FD_CLR(fd, &fdsRead);
1329 if (pdispatcher->GetRequestedEvents() & DE_ACCEPT) {
1330 ff |= DE_ACCEPT;
1331 } else if (errcode || pdispatcher->IsDescriptorClosed()) {
1332 ff |= DE_CLOSE;
1333 } else {
1334 ff |= DE_READ;
1335 }
1336 }
1337
1338 // Check writable descriptors. If we're waiting on a connect, detect
1339 // success versus failure by the reaped error code.
1340 if (FD_ISSET(fd, &fdsWrite)) {
1341 FD_CLR(fd, &fdsWrite);
1342 if (pdispatcher->GetRequestedEvents() & DE_CONNECT) {
1343 if (!errcode) {
1344 ff |= DE_CONNECT;
1345 } else {
1346 ff |= DE_CLOSE;
1347 }
1348 } else {
1349 ff |= DE_WRITE;
1350 }
1351 }
1352
1353 // Tell the descriptor about the event.
1354 if (ff != 0) {
1355 pdispatcher->OnPreEvent(ff);
1356 pdispatcher->OnEvent(ff, errcode);
1357 }
1358 }
1359 }
1360
1361 // Recalc the time remaining to wait. Doing it here means it doesn't get
1362 // calced twice the first time through the loop
1363 if (ptvWait) {
1364 ptvWait->tv_sec = 0;
1365 ptvWait->tv_usec = 0;
1366 struct timeval tvT;
1367 gettimeofday(&tvT, NULL);
1368 if ((tvStop.tv_sec > tvT.tv_sec)
1369 || ((tvStop.tv_sec == tvT.tv_sec)
1370 && (tvStop.tv_usec > tvT.tv_usec))) {
1371 ptvWait->tv_sec = tvStop.tv_sec - tvT.tv_sec;
1372 ptvWait->tv_usec = tvStop.tv_usec - tvT.tv_usec;
1373 if (ptvWait->tv_usec < 0) {
1374 ASSERT(ptvWait->tv_sec > 0);
1375 ptvWait->tv_usec += 1000000;
1376 ptvWait->tv_sec -= 1;
1377 }
1378 }
1379 }
1380 }
1381
1382 return true;
1383}
1384
1385static void GlobalSignalHandler(int signum) {
1386 PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
1387}
1388
1389bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
1390 void (*handler)(int)) {
1391 // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
1392 // otherwise set one.
1393 if (handler == SIG_IGN || handler == SIG_DFL) {
1394 if (!InstallSignal(signum, handler)) {
1395 return false;
1396 }
1397 if (signal_dispatcher_) {
1398 signal_dispatcher_->ClearHandler(signum);
1399 if (!signal_dispatcher_->HasHandlers()) {
1400 signal_dispatcher_.reset();
1401 }
1402 }
1403 } else {
1404 if (!signal_dispatcher_) {
1405 signal_dispatcher_.reset(new PosixSignalDispatcher(this));
1406 }
1407 signal_dispatcher_->SetHandler(signum, handler);
1408 if (!InstallSignal(signum, &GlobalSignalHandler)) {
1409 return false;
1410 }
1411 }
1412 return true;
1413}
1414
1415Dispatcher* PhysicalSocketServer::signal_dispatcher() {
1416 return signal_dispatcher_.get();
1417}
1418
1419bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
1420 struct sigaction act;
1421 // It doesn't really matter what we set this mask to.
1422 if (sigemptyset(&act.sa_mask) != 0) {
1423 LOG_ERR(LS_ERROR) << "Couldn't set mask";
1424 return false;
1425 }
1426 act.sa_handler = handler;
1427#if !defined(__native_client__)
1428 // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
1429 // and it's a nuisance. Though some syscalls still return EINTR and there's no
1430 // real standard for which ones. :(
1431 act.sa_flags = SA_RESTART;
1432#else
1433 act.sa_flags = 0;
1434#endif
1435 if (sigaction(signum, &act, NULL) != 0) {
1436 LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
1437 return false;
1438 }
1439 return true;
1440}
1441#endif // WEBRTC_POSIX
1442
1443#if defined(WEBRTC_WIN)
1444bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
Honghai Zhang82d78622016-05-06 11:29:15 -07001445 int64_t cmsTotal = cmsWait;
1446 int64_t cmsElapsed = 0;
1447 int64_t msStart = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001448
1449 fWait_ = true;
1450 while (fWait_) {
1451 std::vector<WSAEVENT> events;
1452 std::vector<Dispatcher *> event_owners;
1453
1454 events.push_back(socket_ev_);
1455
1456 {
1457 CritScope cr(&crit_);
1458 size_t i = 0;
1459 iterators_.push_back(&i);
1460 // Don't track dispatchers_.size(), because we want to pick up any new
1461 // dispatchers that were added while processing the loop.
1462 while (i < dispatchers_.size()) {
1463 Dispatcher* disp = dispatchers_[i++];
1464 if (!process_io && (disp != signal_wakeup_))
1465 continue;
1466 SOCKET s = disp->GetSocket();
1467 if (disp->CheckSignalClose()) {
1468 // We just signalled close, don't poll this socket
1469 } else if (s != INVALID_SOCKET) {
1470 WSAEventSelect(s,
1471 events[0],
1472 FlagsToEvents(disp->GetRequestedEvents()));
1473 } else {
1474 events.push_back(disp->GetWSAEvent());
1475 event_owners.push_back(disp);
1476 }
1477 }
1478 ASSERT(iterators_.back() == &i);
1479 iterators_.pop_back();
1480 }
1481
1482 // Which is shorter, the delay wait or the asked wait?
1483
Honghai Zhang82d78622016-05-06 11:29:15 -07001484 int64_t cmsNext;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001485 if (cmsWait == kForever) {
1486 cmsNext = cmsWait;
1487 } else {
Honghai Zhang82d78622016-05-06 11:29:15 -07001488 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001489 }
1490
1491 // Wait for one of the events to signal
1492 DWORD dw = WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()),
1493 &events[0],
1494 false,
Honghai Zhang82d78622016-05-06 11:29:15 -07001495 static_cast<DWORD>(cmsNext),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001496 false);
1497
1498 if (dw == WSA_WAIT_FAILED) {
1499 // Failed?
jbauch095ae152015-12-18 01:39:55 -08001500 // TODO(pthatcher): need a better strategy than this!
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001501 WSAGetLastError();
1502 ASSERT(false);
1503 return false;
1504 } else if (dw == WSA_WAIT_TIMEOUT) {
1505 // Timeout?
1506 return true;
1507 } else {
1508 // Figure out which one it is and call it
1509 CritScope cr(&crit_);
1510 int index = dw - WSA_WAIT_EVENT_0;
1511 if (index > 0) {
1512 --index; // The first event is the socket event
1513 event_owners[index]->OnPreEvent(0);
1514 event_owners[index]->OnEvent(0, 0);
1515 } else if (process_io) {
1516 size_t i = 0, end = dispatchers_.size();
1517 iterators_.push_back(&i);
1518 iterators_.push_back(&end); // Don't iterate over new dispatchers.
1519 while (i < end) {
1520 Dispatcher* disp = dispatchers_[i++];
1521 SOCKET s = disp->GetSocket();
1522 if (s == INVALID_SOCKET)
1523 continue;
1524
1525 WSANETWORKEVENTS wsaEvents;
1526 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1527 if (err == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001528 {
1529 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1530 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
1531 LOG(WARNING) << "PhysicalSocketServer got FD_READ_BIT error "
1532 << wsaEvents.iErrorCode[FD_READ_BIT];
1533 }
1534 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1535 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
1536 LOG(WARNING) << "PhysicalSocketServer got FD_WRITE_BIT error "
1537 << wsaEvents.iErrorCode[FD_WRITE_BIT];
1538 }
1539 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1540 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
1541 LOG(WARNING) << "PhysicalSocketServer got FD_CONNECT_BIT error "
1542 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
1543 }
1544 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1545 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
1546 LOG(WARNING) << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1547 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
1548 }
1549 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1550 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
1551 LOG(WARNING) << "PhysicalSocketServer got FD_CLOSE_BIT error "
1552 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
1553 }
1554 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001555 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001556 int errcode = 0;
1557 if (wsaEvents.lNetworkEvents & FD_READ)
1558 ff |= DE_READ;
1559 if (wsaEvents.lNetworkEvents & FD_WRITE)
1560 ff |= DE_WRITE;
1561 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1562 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1563 ff |= DE_CONNECT;
1564 } else {
1565 ff |= DE_CLOSE;
1566 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1567 }
1568 }
1569 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1570 ff |= DE_ACCEPT;
1571 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1572 ff |= DE_CLOSE;
1573 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1574 }
1575 if (ff != 0) {
1576 disp->OnPreEvent(ff);
1577 disp->OnEvent(ff, errcode);
1578 }
1579 }
1580 }
1581 ASSERT(iterators_.back() == &end);
1582 iterators_.pop_back();
1583 ASSERT(iterators_.back() == &i);
1584 iterators_.pop_back();
1585 }
1586
1587 // Reset the network event until new activity occurs
1588 WSAResetEvent(socket_ev_);
1589 }
1590
1591 // Break?
1592 if (!fWait_)
1593 break;
1594 cmsElapsed = TimeSince(msStart);
1595 if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
1596 break;
1597 }
1598 }
1599
1600 // Done
1601 return true;
1602}
honghaizcec0a082016-01-15 14:49:09 -08001603#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001604
1605} // namespace rtc