blob: 8e57d3bb5f765d231d3da61998562982feb244b8 [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
honghaizcec0a082016-01-15 14:49:09 -080010#include "webrtc/base/physicalsocketserver.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000011
12#if defined(_MSC_VER) && _MSC_VER < 1300
13#pragma warning(disable:4786)
14#endif
15
pbos@webrtc.org27e58982014-10-07 17:56:53 +000016#ifdef MEMORY_SANITIZER
17#include <sanitizer/msan_interface.h>
18#endif
19
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000020#if defined(WEBRTC_POSIX)
21#include <string.h>
22#include <errno.h>
23#include <fcntl.h>
Stefan Holmer9131efd2016-05-23 18:19:26 +020024#include <sys/ioctl.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000025#include <sys/time.h>
26#include <sys/select.h>
27#include <unistd.h>
28#include <signal.h>
29#endif
30
31#if defined(WEBRTC_WIN)
32#define WIN32_LEAN_AND_MEAN
33#include <windows.h>
34#include <winsock2.h>
35#include <ws2tcpip.h>
36#undef SetPort
37#endif
38
39#include <algorithm>
40#include <map>
41
tfarina5237aaf2015-11-10 23:44:30 -080042#include "webrtc/base/arraysize.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000043#include "webrtc/base/basictypes.h"
44#include "webrtc/base/byteorder.h"
nissec80e7412017-01-11 05:56:46 -080045#include "webrtc/base/checks.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000046#include "webrtc/base/logging.h"
honghaizcec0a082016-01-15 14:49:09 -080047#include "webrtc/base/networkmonitor.h"
danilchapbebf54c2016-04-28 01:32:48 -070048#include "webrtc/base/nullsocketserver.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000049#include "webrtc/base/timeutils.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000050#include "webrtc/base/win32socketinit.h"
51
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000052#if defined(WEBRTC_POSIX)
53#include <netinet/tcp.h> // for TCP_NODELAY
54#define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h
55typedef void* SockOptArg;
Stefan Holmer9131efd2016-05-23 18:19:26 +020056
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000057#endif // WEBRTC_POSIX
58
Stefan Holmer3ebb3ef2016-05-23 20:26:11 +020059#if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) && !defined(__native_client__)
60
Stefan Holmer9131efd2016-05-23 18:19:26 +020061int64_t GetSocketRecvTimestamp(int socket) {
62 struct timeval tv_ioctl;
63 int ret = ioctl(socket, SIOCGSTAMP, &tv_ioctl);
64 if (ret != 0)
65 return -1;
66 int64_t timestamp =
67 rtc::kNumMicrosecsPerSec * static_cast<int64_t>(tv_ioctl.tv_sec) +
68 static_cast<int64_t>(tv_ioctl.tv_usec);
69 return timestamp;
70}
71
72#else
73
74int64_t GetSocketRecvTimestamp(int socket) {
75 return -1;
76}
77#endif
78
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000079#if defined(WEBRTC_WIN)
80typedef char* SockOptArg;
81#endif
82
83namespace rtc {
84
danilchapbebf54c2016-04-28 01:32:48 -070085std::unique_ptr<SocketServer> SocketServer::CreateDefault() {
86#if defined(__native_client__)
87 return std::unique_ptr<SocketServer>(new rtc::NullSocketServer);
88#else
89 return std::unique_ptr<SocketServer>(new rtc::PhysicalSocketServer);
90#endif
91}
92
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000093#if defined(WEBRTC_WIN)
94// Standard MTUs, from RFC 1191
Peter Boström0c4e06b2015-10-07 12:23:21 +020095const uint16_t PACKET_MAXIMUMS[] = {
96 65535, // Theoretical maximum, Hyperchannel
97 32000, // Nothing
98 17914, // 16Mb IBM Token Ring
99 8166, // IEEE 802.4
100 // 4464, // IEEE 802.5 (4Mb max)
101 4352, // FDDI
102 // 2048, // Wideband Network
103 2002, // IEEE 802.5 (4Mb recommended)
104 // 1536, // Expermental Ethernet Networks
105 // 1500, // Ethernet, Point-to-Point (default)
106 1492, // IEEE 802.3
107 1006, // SLIP, ARPANET
108 // 576, // X.25 Networks
109 // 544, // DEC IP Portal
110 // 512, // NETBIOS
111 508, // IEEE 802/Source-Rt Bridge, ARCNET
112 296, // Point-to-Point (low delay)
113 68, // Official minimum
114 0, // End of list marker
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000115};
116
117static const int IP_HEADER_SIZE = 20u;
118static const int IPV6_HEADER_SIZE = 40u;
119static const int ICMP_HEADER_SIZE = 8u;
120static const int ICMP_PING_TIMEOUT_MILLIS = 10000u;
121#endif
122
jbauch095ae152015-12-18 01:39:55 -0800123PhysicalSocket::PhysicalSocket(PhysicalSocketServer* ss, SOCKET s)
124 : ss_(ss), s_(s), enabled_events_(0), error_(0),
125 state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED),
126 resolver_(nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000127#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800128 // EnsureWinsockInit() ensures that winsock is initialized. The default
129 // version of this function doesn't do anything because winsock is
130 // initialized by constructor of a static object. If neccessary libjingle
131 // users can link it with a different version of this function by replacing
132 // win32socketinit.cc. See win32socketinit.cc for more details.
133 EnsureWinsockInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000134#endif
jbauch095ae152015-12-18 01:39:55 -0800135 if (s_ != INVALID_SOCKET) {
136 enabled_events_ = DE_READ | DE_WRITE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000137
jbauch095ae152015-12-18 01:39:55 -0800138 int type = SOCK_STREAM;
139 socklen_t len = sizeof(type);
nissec16fa5e2017-02-07 07:18:43 -0800140 const int res =
141 getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len);
142 RTC_DCHECK_EQ(0, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000143 udp_ = (SOCK_DGRAM == type);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000144 }
jbauch095ae152015-12-18 01:39:55 -0800145}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000146
jbauch095ae152015-12-18 01:39:55 -0800147PhysicalSocket::~PhysicalSocket() {
148 Close();
149}
150
151bool PhysicalSocket::Create(int family, int type) {
152 Close();
153 s_ = ::socket(family, type, 0);
154 udp_ = (SOCK_DGRAM == type);
155 UpdateLastError();
156 if (udp_)
157 enabled_events_ = DE_READ | DE_WRITE;
158 return s_ != INVALID_SOCKET;
159}
160
161SocketAddress PhysicalSocket::GetLocalAddress() const {
162 sockaddr_storage addr_storage = {0};
163 socklen_t addrlen = sizeof(addr_storage);
164 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
165 int result = ::getsockname(s_, addr, &addrlen);
166 SocketAddress address;
167 if (result >= 0) {
168 SocketAddressFromSockAddrStorage(addr_storage, &address);
169 } else {
170 LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
171 << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000172 }
jbauch095ae152015-12-18 01:39:55 -0800173 return address;
174}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000175
jbauch095ae152015-12-18 01:39:55 -0800176SocketAddress PhysicalSocket::GetRemoteAddress() const {
177 sockaddr_storage addr_storage = {0};
178 socklen_t addrlen = sizeof(addr_storage);
179 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
180 int result = ::getpeername(s_, addr, &addrlen);
181 SocketAddress address;
182 if (result >= 0) {
183 SocketAddressFromSockAddrStorage(addr_storage, &address);
184 } else {
185 LOG(LS_WARNING) << "GetRemoteAddress: unable to get remote addr, socket="
186 << s_;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000187 }
jbauch095ae152015-12-18 01:39:55 -0800188 return address;
189}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000190
jbauch095ae152015-12-18 01:39:55 -0800191int PhysicalSocket::Bind(const SocketAddress& bind_addr) {
deadbeefc874d122017-02-13 15:41:59 -0800192 SocketAddress copied_bind_addr = bind_addr;
193 // If a network binder is available, use it to bind a socket to an interface
194 // instead of bind(), since this is more reliable on an OS with a weak host
195 // model.
deadbeef9ffa13f2017-02-21 16:18:00 -0800196 if (ss_->network_binder() && !bind_addr.IsAnyIP()) {
deadbeefc874d122017-02-13 15:41:59 -0800197 NetworkBindingResult result =
198 ss_->network_binder()->BindSocketToNetwork(s_, bind_addr.ipaddr());
199 if (result == NetworkBindingResult::SUCCESS) {
200 // Since the network binder handled binding the socket to the desired
201 // network interface, we don't need to (and shouldn't) include an IP in
202 // the bind() call; bind() just needs to assign a port.
203 copied_bind_addr.SetIP(GetAnyIP(copied_bind_addr.ipaddr().family()));
204 } else if (result == NetworkBindingResult::NOT_IMPLEMENTED) {
205 LOG(LS_INFO) << "Can't bind socket to network because "
206 "network binding is not implemented for this OS.";
207 } else {
208 if (bind_addr.IsLoopbackIP()) {
209 // If we couldn't bind to a loopback IP (which should only happen in
210 // test scenarios), continue on. This may be expected behavior.
211 LOG(LS_VERBOSE) << "Binding socket to loopback address "
212 << bind_addr.ipaddr().ToString()
213 << " failed; result: " << static_cast<int>(result);
214 } else {
215 LOG(LS_WARNING) << "Binding socket to network address "
216 << bind_addr.ipaddr().ToString()
217 << " failed; result: " << static_cast<int>(result);
218 // If a network binding was attempted and failed, we should stop here
219 // and not try to use the socket. Otherwise, we may end up sending
220 // packets with an invalid source address.
221 // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=7026
222 return -1;
223 }
224 }
225 }
jbauch095ae152015-12-18 01:39:55 -0800226 sockaddr_storage addr_storage;
deadbeefc874d122017-02-13 15:41:59 -0800227 size_t len = copied_bind_addr.ToSockAddrStorage(&addr_storage);
jbauch095ae152015-12-18 01:39:55 -0800228 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
229 int err = ::bind(s_, addr, static_cast<int>(len));
230 UpdateLastError();
tfarinaa41ab932015-10-30 16:08:48 -0700231#if !defined(NDEBUG)
jbauch095ae152015-12-18 01:39:55 -0800232 if (0 == err) {
233 dbg_addr_ = "Bound @ ";
234 dbg_addr_.append(GetLocalAddress().ToString());
235 }
tfarinaa41ab932015-10-30 16:08:48 -0700236#endif
jbauch095ae152015-12-18 01:39:55 -0800237 return err;
238}
239
240int PhysicalSocket::Connect(const SocketAddress& addr) {
241 // TODO(pthatcher): Implicit creation is required to reconnect...
242 // ...but should we make it more explicit?
243 if (state_ != CS_CLOSED) {
244 SetError(EALREADY);
245 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000246 }
jbauch095ae152015-12-18 01:39:55 -0800247 if (addr.IsUnresolvedIP()) {
248 LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
249 resolver_ = new AsyncResolver();
250 resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult);
251 resolver_->Start(addr);
252 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000253 return 0;
254 }
255
jbauch095ae152015-12-18 01:39:55 -0800256 return DoConnect(addr);
257}
258
259int PhysicalSocket::DoConnect(const SocketAddress& connect_addr) {
260 if ((s_ == INVALID_SOCKET) &&
261 !Create(connect_addr.family(), SOCK_STREAM)) {
262 return SOCKET_ERROR;
263 }
264 sockaddr_storage addr_storage;
265 size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
266 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
267 int err = ::connect(s_, addr, static_cast<int>(len));
268 UpdateLastError();
269 if (err == 0) {
270 state_ = CS_CONNECTED;
271 } else if (IsBlockingError(GetError())) {
272 state_ = CS_CONNECTING;
273 enabled_events_ |= DE_CONNECT;
274 } else {
275 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000276 }
277
jbauch095ae152015-12-18 01:39:55 -0800278 enabled_events_ |= DE_READ | DE_WRITE;
279 return 0;
280}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000281
jbauch095ae152015-12-18 01:39:55 -0800282int PhysicalSocket::GetError() const {
283 CritScope cs(&crit_);
284 return error_;
285}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000286
jbauch095ae152015-12-18 01:39:55 -0800287void PhysicalSocket::SetError(int error) {
288 CritScope cs(&crit_);
289 error_ = error;
290}
291
292AsyncSocket::ConnState PhysicalSocket::GetState() const {
293 return state_;
294}
295
296int PhysicalSocket::GetOption(Option opt, int* value) {
297 int slevel;
298 int sopt;
299 if (TranslateOption(opt, &slevel, &sopt) == -1)
300 return -1;
301 socklen_t optlen = sizeof(*value);
302 int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
303 if (ret != -1 && opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000304#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800305 *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000306#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000307 }
jbauch095ae152015-12-18 01:39:55 -0800308 return ret;
309}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000310
jbauch095ae152015-12-18 01:39:55 -0800311int PhysicalSocket::SetOption(Option opt, int value) {
312 int slevel;
313 int sopt;
314 if (TranslateOption(opt, &slevel, &sopt) == -1)
315 return -1;
316 if (opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000317#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800318 value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000319#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000320 }
jbauch095ae152015-12-18 01:39:55 -0800321 return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
322}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000323
jbauch095ae152015-12-18 01:39:55 -0800324int PhysicalSocket::Send(const void* pv, size_t cb) {
jbauchf2a2bf42016-02-03 16:45:32 -0800325 int sent = DoSend(s_, reinterpret_cast<const char *>(pv),
326 static_cast<int>(cb),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000327#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800328 // Suppress SIGPIPE. Without this, attempting to send on a socket whose
329 // other end is closed will result in a SIGPIPE signal being raised to
330 // our process, which by default will terminate the process, which we
331 // don't want. By specifying this flag, we'll just get the error EPIPE
332 // instead and can handle the error gracefully.
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 );
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>(cb));
jbauchf2a2bf42016-02-03 16:45:32 -0800342 if ((sent > 0 && sent < static_cast<int>(cb)) ||
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
jbauch095ae152015-12-18 01:39:55 -0800349int PhysicalSocket::SendTo(const void* buffer,
350 size_t length,
351 const SocketAddress& addr) {
352 sockaddr_storage saddr;
353 size_t len = addr.ToSockAddrStorage(&saddr);
jbauchf2a2bf42016-02-03 16:45:32 -0800354 int sent = DoSendTo(
jbauch095ae152015-12-18 01:39:55 -0800355 s_, static_cast<const char *>(buffer), static_cast<int>(length),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000356#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800357 // Suppress SIGPIPE. See above for explanation.
358 MSG_NOSIGNAL,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000359#else
jbauch095ae152015-12-18 01:39:55 -0800360 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000361#endif
jbauch095ae152015-12-18 01:39:55 -0800362 reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
363 UpdateLastError();
364 MaybeRemapSendError();
365 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800366 RTC_DCHECK(sent <= static_cast<int>(length));
jbauchf2a2bf42016-02-03 16:45:32 -0800367 if ((sent > 0 && sent < static_cast<int>(length)) ||
368 (sent < 0 && IsBlockingError(GetError()))) {
jbauch095ae152015-12-18 01:39:55 -0800369 enabled_events_ |= DE_WRITE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000370 }
jbauch095ae152015-12-18 01:39:55 -0800371 return sent;
372}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000373
Stefan Holmer9131efd2016-05-23 18:19:26 +0200374int PhysicalSocket::Recv(void* buffer, size_t length, int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800375 int received = ::recv(s_, static_cast<char*>(buffer),
376 static_cast<int>(length), 0);
377 if ((received == 0) && (length != 0)) {
378 // Note: on graceful shutdown, recv can return 0. In this case, we
379 // pretend it is blocking, and then signal close, so that simplifying
380 // assumptions can be made about Recv.
381 LOG(LS_WARNING) << "EOF from socket; deferring close event";
382 // Must turn this back on so that the select() loop will notice the close
383 // event.
384 enabled_events_ |= DE_READ;
385 SetError(EWOULDBLOCK);
386 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000387 }
Stefan Holmer9131efd2016-05-23 18:19:26 +0200388 if (timestamp) {
389 *timestamp = GetSocketRecvTimestamp(s_);
390 }
jbauch095ae152015-12-18 01:39:55 -0800391 UpdateLastError();
392 int error = GetError();
393 bool success = (received >= 0) || IsBlockingError(error);
394 if (udp_ || success) {
395 enabled_events_ |= DE_READ;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000396 }
jbauch095ae152015-12-18 01:39:55 -0800397 if (!success) {
398 LOG_F(LS_VERBOSE) << "Error = " << error;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000399 }
jbauch095ae152015-12-18 01:39:55 -0800400 return received;
401}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000402
jbauch095ae152015-12-18 01:39:55 -0800403int PhysicalSocket::RecvFrom(void* buffer,
404 size_t length,
Stefan Holmer9131efd2016-05-23 18:19:26 +0200405 SocketAddress* out_addr,
406 int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800407 sockaddr_storage addr_storage;
408 socklen_t addr_len = sizeof(addr_storage);
409 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
410 int received = ::recvfrom(s_, static_cast<char*>(buffer),
411 static_cast<int>(length), 0, addr, &addr_len);
Stefan Holmer9131efd2016-05-23 18:19:26 +0200412 if (timestamp) {
413 *timestamp = GetSocketRecvTimestamp(s_);
414 }
jbauch095ae152015-12-18 01:39:55 -0800415 UpdateLastError();
416 if ((received >= 0) && (out_addr != nullptr))
417 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
418 int error = GetError();
419 bool success = (received >= 0) || IsBlockingError(error);
420 if (udp_ || success) {
421 enabled_events_ |= DE_READ;
422 }
423 if (!success) {
424 LOG_F(LS_VERBOSE) << "Error = " << error;
425 }
426 return received;
427}
428
429int PhysicalSocket::Listen(int backlog) {
430 int err = ::listen(s_, backlog);
431 UpdateLastError();
432 if (err == 0) {
433 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000434 enabled_events_ |= DE_ACCEPT;
jbauch095ae152015-12-18 01:39:55 -0800435#if !defined(NDEBUG)
436 dbg_addr_ = "Listening @ ";
437 dbg_addr_.append(GetLocalAddress().ToString());
438#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000439 }
jbauch095ae152015-12-18 01:39:55 -0800440 return err;
441}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000442
jbauch095ae152015-12-18 01:39:55 -0800443AsyncSocket* PhysicalSocket::Accept(SocketAddress* out_addr) {
444 // Always re-subscribe DE_ACCEPT to make sure new incoming connections will
445 // trigger an event even if DoAccept returns an error here.
446 enabled_events_ |= DE_ACCEPT;
447 sockaddr_storage addr_storage;
448 socklen_t addr_len = sizeof(addr_storage);
449 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
450 SOCKET s = DoAccept(s_, addr, &addr_len);
451 UpdateLastError();
452 if (s == INVALID_SOCKET)
453 return nullptr;
454 if (out_addr != nullptr)
455 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
456 return ss_->WrapSocket(s);
457}
458
459int PhysicalSocket::Close() {
460 if (s_ == INVALID_SOCKET)
461 return 0;
462 int err = ::closesocket(s_);
463 UpdateLastError();
464 s_ = INVALID_SOCKET;
465 state_ = CS_CLOSED;
466 enabled_events_ = 0;
467 if (resolver_) {
468 resolver_->Destroy(false);
469 resolver_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000470 }
jbauch095ae152015-12-18 01:39:55 -0800471 return err;
472}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000473
jbauch095ae152015-12-18 01:39:55 -0800474SOCKET PhysicalSocket::DoAccept(SOCKET socket,
475 sockaddr* addr,
476 socklen_t* addrlen) {
477 return ::accept(socket, addr, addrlen);
478}
479
jbauchf2a2bf42016-02-03 16:45:32 -0800480int PhysicalSocket::DoSend(SOCKET socket, const char* buf, int len, int flags) {
481 return ::send(socket, buf, len, flags);
482}
483
484int PhysicalSocket::DoSendTo(SOCKET socket,
485 const char* buf,
486 int len,
487 int flags,
488 const struct sockaddr* dest_addr,
489 socklen_t addrlen) {
490 return ::sendto(socket, buf, len, flags, dest_addr, addrlen);
491}
492
jbauch095ae152015-12-18 01:39:55 -0800493void PhysicalSocket::OnResolveResult(AsyncResolverInterface* resolver) {
494 if (resolver != resolver_) {
495 return;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000496 }
497
jbauch095ae152015-12-18 01:39:55 -0800498 int error = resolver_->GetError();
499 if (error == 0) {
500 error = DoConnect(resolver_->address());
501 } else {
502 Close();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000503 }
504
jbauch095ae152015-12-18 01:39:55 -0800505 if (error) {
506 SetError(error);
507 SignalCloseEvent(this, error);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000508 }
jbauch095ae152015-12-18 01:39:55 -0800509}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000510
jbauch095ae152015-12-18 01:39:55 -0800511void PhysicalSocket::UpdateLastError() {
512 SetError(LAST_SYSTEM_ERROR);
513}
514
515void PhysicalSocket::MaybeRemapSendError() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000516#if defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800517 // https://developer.apple.com/library/mac/documentation/Darwin/
518 // Reference/ManPages/man2/sendto.2.html
519 // ENOBUFS - The output queue for a network interface is full.
520 // This generally indicates that the interface has stopped sending,
521 // but may be caused by transient congestion.
522 if (GetError() == ENOBUFS) {
523 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000524 }
jbauch095ae152015-12-18 01:39:55 -0800525#endif
526}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000527
jbauch095ae152015-12-18 01:39:55 -0800528int PhysicalSocket::TranslateOption(Option opt, int* slevel, int* sopt) {
529 switch (opt) {
530 case OPT_DONTFRAGMENT:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000531#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800532 *slevel = IPPROTO_IP;
533 *sopt = IP_DONTFRAGMENT;
534 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000535#elif defined(WEBRTC_MAC) || defined(BSD) || defined(__native_client__)
jbauch095ae152015-12-18 01:39:55 -0800536 LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
537 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000538#elif defined(WEBRTC_POSIX)
jbauch095ae152015-12-18 01:39:55 -0800539 *slevel = IPPROTO_IP;
540 *sopt = IP_MTU_DISCOVER;
541 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000542#endif
jbauch095ae152015-12-18 01:39:55 -0800543 case OPT_RCVBUF:
544 *slevel = SOL_SOCKET;
545 *sopt = SO_RCVBUF;
546 break;
547 case OPT_SNDBUF:
548 *slevel = SOL_SOCKET;
549 *sopt = SO_SNDBUF;
550 break;
551 case OPT_NODELAY:
552 *slevel = IPPROTO_TCP;
553 *sopt = TCP_NODELAY;
554 break;
555 case OPT_DSCP:
556 LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
557 return -1;
558 case OPT_RTP_SENDTIME_EXTN_ID:
559 return -1; // No logging is necessary as this not a OS socket option.
560 default:
nissec80e7412017-01-11 05:56:46 -0800561 RTC_NOTREACHED();
jbauch095ae152015-12-18 01:39:55 -0800562 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000563 }
jbauch095ae152015-12-18 01:39:55 -0800564 return 0;
565}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000566
jbauch4331fcd2016-01-06 22:20:28 -0800567SocketDispatcher::SocketDispatcher(PhysicalSocketServer *ss)
568#if defined(WEBRTC_WIN)
569 : PhysicalSocket(ss), id_(0), signal_close_(false)
570#else
571 : PhysicalSocket(ss)
572#endif
573{
574}
575
576SocketDispatcher::SocketDispatcher(SOCKET s, PhysicalSocketServer *ss)
577#if defined(WEBRTC_WIN)
578 : PhysicalSocket(ss, s), id_(0), signal_close_(false)
579#else
580 : PhysicalSocket(ss, s)
581#endif
582{
583}
584
585SocketDispatcher::~SocketDispatcher() {
586 Close();
587}
588
589bool SocketDispatcher::Initialize() {
nisseede5da42017-01-12 05:15:36 -0800590 RTC_DCHECK(s_ != INVALID_SOCKET);
jbauch4331fcd2016-01-06 22:20:28 -0800591 // Must be a non-blocking
592#if defined(WEBRTC_WIN)
593 u_long argp = 1;
594 ioctlsocket(s_, FIONBIO, &argp);
595#elif defined(WEBRTC_POSIX)
596 fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
597#endif
598 ss_->Add(this);
599 return true;
600}
601
602bool SocketDispatcher::Create(int type) {
603 return Create(AF_INET, type);
604}
605
606bool SocketDispatcher::Create(int family, int type) {
607 // Change the socket to be non-blocking.
608 if (!PhysicalSocket::Create(family, type))
609 return false;
610
611 if (!Initialize())
612 return false;
613
614#if defined(WEBRTC_WIN)
615 do { id_ = ++next_id_; } while (id_ == 0);
616#endif
617 return true;
618}
619
620#if defined(WEBRTC_WIN)
621
622WSAEVENT SocketDispatcher::GetWSAEvent() {
623 return WSA_INVALID_EVENT;
624}
625
626SOCKET SocketDispatcher::GetSocket() {
627 return s_;
628}
629
630bool SocketDispatcher::CheckSignalClose() {
631 if (!signal_close_)
632 return false;
633
634 char ch;
635 if (recv(s_, &ch, 1, MSG_PEEK) > 0)
636 return false;
637
638 state_ = CS_CLOSED;
639 signal_close_ = false;
640 SignalCloseEvent(this, signal_err_);
641 return true;
642}
643
644int SocketDispatcher::next_id_ = 0;
645
646#elif defined(WEBRTC_POSIX)
647
648int SocketDispatcher::GetDescriptor() {
649 return s_;
650}
651
652bool SocketDispatcher::IsDescriptorClosed() {
deadbeeffaedf7f2017-02-09 15:09:22 -0800653 if (udp_) {
654 // The MSG_PEEK trick doesn't work for UDP, since (at least in some
655 // circumstances) it requires reading an entire UDP packet, which would be
656 // bad for performance here. So, just check whether |s_| has been closed,
657 // which should be sufficient.
658 return s_ == INVALID_SOCKET;
659 }
jbauch4331fcd2016-01-06 22:20:28 -0800660 // We don't have a reliable way of distinguishing end-of-stream
661 // from readability. So test on each readable call. Is this
662 // inefficient? Probably.
663 char ch;
664 ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
665 if (res > 0) {
666 // Data available, so not closed.
667 return false;
668 } else if (res == 0) {
669 // EOF, so closed.
670 return true;
671 } else { // error
672 switch (errno) {
673 // Returned if we've already closed s_.
674 case EBADF:
675 // Returned during ungraceful peer shutdown.
676 case ECONNRESET:
677 return true;
deadbeeffaedf7f2017-02-09 15:09:22 -0800678 // The normal blocking error; don't log anything.
679 case EWOULDBLOCK:
680 // Interrupted system call.
681 case EINTR:
682 return false;
jbauch4331fcd2016-01-06 22:20:28 -0800683 default:
684 // Assume that all other errors are just blocking errors, meaning the
685 // connection is still good but we just can't read from it right now.
686 // This should only happen when connecting (and at most once), because
687 // in all other cases this function is only called if the file
688 // descriptor is already known to be in the readable state. However,
689 // it's not necessary a problem if we spuriously interpret a
690 // "connection lost"-type error as a blocking error, because typically
691 // the next recv() will get EOF, so we'll still eventually notice that
692 // the socket is closed.
693 LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
694 return false;
695 }
696 }
697}
698
699#endif // WEBRTC_POSIX
700
701uint32_t SocketDispatcher::GetRequestedEvents() {
702 return enabled_events_;
703}
704
705void SocketDispatcher::OnPreEvent(uint32_t ff) {
706 if ((ff & DE_CONNECT) != 0)
707 state_ = CS_CONNECTED;
708
709#if defined(WEBRTC_WIN)
710 // We set CS_CLOSED from CheckSignalClose.
711#elif defined(WEBRTC_POSIX)
712 if ((ff & DE_CLOSE) != 0)
713 state_ = CS_CLOSED;
714#endif
715}
716
717#if defined(WEBRTC_WIN)
718
719void SocketDispatcher::OnEvent(uint32_t ff, int err) {
720 int cache_id = id_;
721 // Make sure we deliver connect/accept first. Otherwise, consumers may see
722 // something like a READ followed by a CONNECT, which would be odd.
723 if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
724 if (ff != DE_CONNECT)
725 LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
726 enabled_events_ &= ~DE_CONNECT;
727#if !defined(NDEBUG)
728 dbg_addr_ = "Connected @ ";
729 dbg_addr_.append(GetRemoteAddress().ToString());
730#endif
731 SignalConnectEvent(this);
732 }
733 if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
734 enabled_events_ &= ~DE_ACCEPT;
735 SignalReadEvent(this);
736 }
737 if ((ff & DE_READ) != 0) {
738 enabled_events_ &= ~DE_READ;
739 SignalReadEvent(this);
740 }
741 if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
742 enabled_events_ &= ~DE_WRITE;
743 SignalWriteEvent(this);
744 }
745 if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
746 signal_close_ = true;
747 signal_err_ = err;
748 }
749}
750
751#elif defined(WEBRTC_POSIX)
752
753void SocketDispatcher::OnEvent(uint32_t ff, int err) {
754 // Make sure we deliver connect/accept first. Otherwise, consumers may see
755 // something like a READ followed by a CONNECT, which would be odd.
756 if ((ff & DE_CONNECT) != 0) {
757 enabled_events_ &= ~DE_CONNECT;
758 SignalConnectEvent(this);
759 }
760 if ((ff & DE_ACCEPT) != 0) {
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) {
769 enabled_events_ &= ~DE_WRITE;
770 SignalWriteEvent(this);
771 }
772 if ((ff & DE_CLOSE) != 0) {
773 // The socket is now dead to us, so stop checking it.
774 enabled_events_ = 0;
775 SignalCloseEvent(this, err);
776 }
777}
778
779#endif // WEBRTC_POSIX
780
781int SocketDispatcher::Close() {
782 if (s_ == INVALID_SOCKET)
783 return 0;
784
785#if defined(WEBRTC_WIN)
786 id_ = 0;
787 signal_close_ = false;
788#endif
789 ss_->Remove(this);
790 return PhysicalSocket::Close();
791}
792
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000793#if defined(WEBRTC_POSIX)
794class EventDispatcher : public Dispatcher {
795 public:
796 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
797 if (pipe(afd_) < 0)
798 LOG(LERROR) << "pipe failed";
799 ss_->Add(this);
800 }
801
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000802 ~EventDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000803 ss_->Remove(this);
804 close(afd_[0]);
805 close(afd_[1]);
806 }
807
808 virtual void Signal() {
809 CritScope cs(&crit_);
810 if (!fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200811 const uint8_t b[1] = {0};
nissec16fa5e2017-02-07 07:18:43 -0800812 const ssize_t res = write(afd_[1], b, sizeof(b));
813 RTC_DCHECK_EQ(1, res);
814 fSignaled_ = true;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000815 }
816 }
817
Peter Boström0c4e06b2015-10-07 12:23:21 +0200818 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000819
Peter Boström0c4e06b2015-10-07 12:23:21 +0200820 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000821 // It is not possible to perfectly emulate an auto-resetting event with
822 // pipes. This simulates it by resetting before the event is handled.
823
824 CritScope cs(&crit_);
825 if (fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200826 uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
nissec16fa5e2017-02-07 07:18:43 -0800827 const ssize_t res = read(afd_[0], b, sizeof(b));
828 RTC_DCHECK_EQ(1, res);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000829 fSignaled_ = false;
830 }
831 }
832
nissec80e7412017-01-11 05:56:46 -0800833 void OnEvent(uint32_t ff, int err) override { RTC_NOTREACHED(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000834
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000835 int GetDescriptor() override { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000836
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000837 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000838
839 private:
840 PhysicalSocketServer *ss_;
841 int afd_[2];
842 bool fSignaled_;
843 CriticalSection crit_;
844};
845
846// These two classes use the self-pipe trick to deliver POSIX signals to our
847// select loop. This is the only safe, reliable, cross-platform way to do
848// non-trivial things with a POSIX signal in an event-driven program (until
849// proper pselect() implementations become ubiquitous).
850
851class PosixSignalHandler {
852 public:
853 // POSIX only specifies 32 signals, but in principle the system might have
854 // more and the programmer might choose to use them, so we size our array
855 // for 128.
856 static const int kNumPosixSignals = 128;
857
858 // There is just a single global instance. (Signal handlers do not get any
859 // sort of user-defined void * parameter, so they can't access anything that
860 // isn't global.)
861 static PosixSignalHandler* Instance() {
Andrew MacDonald469c2c02015-05-22 17:50:26 -0700862 RTC_DEFINE_STATIC_LOCAL(PosixSignalHandler, instance, ());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000863 return &instance;
864 }
865
866 // Returns true if the given signal number is set.
867 bool IsSignalSet(int signum) const {
nisseede5da42017-01-12 05:15:36 -0800868 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800869 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000870 return received_signal_[signum];
871 } else {
872 return false;
873 }
874 }
875
876 // Clears the given signal number.
877 void ClearSignal(int signum) {
nisseede5da42017-01-12 05:15:36 -0800878 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800879 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000880 received_signal_[signum] = false;
881 }
882 }
883
884 // Returns the file descriptor to monitor for signal events.
885 int GetDescriptor() const {
886 return afd_[0];
887 }
888
889 // This is called directly from our real signal handler, so it must be
890 // signal-handler-safe. That means it cannot assume anything about the
891 // user-level state of the process, since the handler could be executed at any
892 // time on any thread.
893 void OnPosixSignalReceived(int signum) {
tfarina5237aaf2015-11-10 23:44:30 -0800894 if (signum >= static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000895 // We don't have space in our array for this.
896 return;
897 }
898 // Set a flag saying we've seen this signal.
899 received_signal_[signum] = true;
900 // Notify application code that we got a signal.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200901 const uint8_t b[1] = {0};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000902 if (-1 == write(afd_[1], b, sizeof(b))) {
903 // Nothing we can do here. If there's an error somehow then there's
904 // nothing we can safely do from a signal handler.
905 // No, we can't even safely log it.
906 // But, we still have to check the return value here. Otherwise,
907 // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
908 return;
909 }
910 }
911
912 private:
913 PosixSignalHandler() {
914 if (pipe(afd_) < 0) {
915 LOG_ERR(LS_ERROR) << "pipe failed";
916 return;
917 }
918 if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
919 LOG_ERR(LS_WARNING) << "fcntl #1 failed";
920 }
921 if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
922 LOG_ERR(LS_WARNING) << "fcntl #2 failed";
923 }
924 memset(const_cast<void *>(static_cast<volatile void *>(received_signal_)),
925 0,
926 sizeof(received_signal_));
927 }
928
929 ~PosixSignalHandler() {
930 int fd1 = afd_[0];
931 int fd2 = afd_[1];
932 // We clobber the stored file descriptor numbers here or else in principle
933 // a signal that happens to be delivered during application termination
934 // could erroneously write a zero byte to an unrelated file handle in
935 // OnPosixSignalReceived() if some other file happens to be opened later
936 // during shutdown and happens to be given the same file descriptor number
937 // as our pipe had. Unfortunately even with this precaution there is still a
938 // race where that could occur if said signal happens to be handled
939 // concurrently with this code and happens to have already read the value of
940 // afd_[1] from memory before we clobber it, but that's unlikely.
941 afd_[0] = -1;
942 afd_[1] = -1;
943 close(fd1);
944 close(fd2);
945 }
946
947 int afd_[2];
948 // These are boolean flags that will be set in our signal handler and read
949 // and cleared from Wait(). There is a race involved in this, but it is
950 // benign. The signal handler sets the flag before signaling the pipe, so
951 // we'll never end up blocking in select() while a flag is still true.
952 // However, if two of the same signal arrive close to each other then it's
953 // possible that the second time the handler may set the flag while it's still
954 // true, meaning that signal will be missed. But the first occurrence of it
955 // will still be handled, so this isn't a problem.
956 // Volatile is not necessary here for correctness, but this data _is_ volatile
957 // so I've marked it as such.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200958 volatile uint8_t received_signal_[kNumPosixSignals];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000959};
960
961class PosixSignalDispatcher : public Dispatcher {
962 public:
963 PosixSignalDispatcher(PhysicalSocketServer *owner) : owner_(owner) {
964 owner_->Add(this);
965 }
966
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000967 ~PosixSignalDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000968 owner_->Remove(this);
969 }
970
Peter Boström0c4e06b2015-10-07 12:23:21 +0200971 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000972
Peter Boström0c4e06b2015-10-07 12:23:21 +0200973 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000974 // Events might get grouped if signals come very fast, so we read out up to
975 // 16 bytes to make sure we keep the pipe empty.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200976 uint8_t b[16];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000977 ssize_t ret = read(GetDescriptor(), b, sizeof(b));
978 if (ret < 0) {
979 LOG_ERR(LS_WARNING) << "Error in read()";
980 } else if (ret == 0) {
981 LOG(LS_WARNING) << "Should have read at least one byte";
982 }
983 }
984
Peter Boström0c4e06b2015-10-07 12:23:21 +0200985 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000986 for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
987 ++signum) {
988 if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
989 PosixSignalHandler::Instance()->ClearSignal(signum);
990 HandlerMap::iterator i = handlers_.find(signum);
991 if (i == handlers_.end()) {
992 // This can happen if a signal is delivered to our process at around
993 // the same time as we unset our handler for it. It is not an error
994 // condition, but it's unusual enough to be worth logging.
995 LOG(LS_INFO) << "Received signal with no handler: " << signum;
996 } else {
997 // Otherwise, execute our handler.
998 (*i->second)(signum);
999 }
1000 }
1001 }
1002 }
1003
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001004 int GetDescriptor() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001005 return PosixSignalHandler::Instance()->GetDescriptor();
1006 }
1007
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001008 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001009
1010 void SetHandler(int signum, void (*handler)(int)) {
1011 handlers_[signum] = handler;
1012 }
1013
1014 void ClearHandler(int signum) {
1015 handlers_.erase(signum);
1016 }
1017
1018 bool HasHandlers() {
1019 return !handlers_.empty();
1020 }
1021
1022 private:
1023 typedef std::map<int, void (*)(int)> HandlerMap;
1024
1025 HandlerMap handlers_;
1026 // Our owner.
1027 PhysicalSocketServer *owner_;
1028};
1029
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001030#endif // WEBRTC_POSIX
1031
1032#if defined(WEBRTC_WIN)
Peter Boström0c4e06b2015-10-07 12:23:21 +02001033static uint32_t FlagsToEvents(uint32_t events) {
1034 uint32_t ffFD = FD_CLOSE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001035 if (events & DE_READ)
1036 ffFD |= FD_READ;
1037 if (events & DE_WRITE)
1038 ffFD |= FD_WRITE;
1039 if (events & DE_CONNECT)
1040 ffFD |= FD_CONNECT;
1041 if (events & DE_ACCEPT)
1042 ffFD |= FD_ACCEPT;
1043 return ffFD;
1044}
1045
1046class EventDispatcher : public Dispatcher {
1047 public:
1048 EventDispatcher(PhysicalSocketServer *ss) : ss_(ss) {
1049 hev_ = WSACreateEvent();
1050 if (hev_) {
1051 ss_->Add(this);
1052 }
1053 }
1054
1055 ~EventDispatcher() {
deadbeef37f5ecf2017-02-27 14:06:41 -08001056 if (hev_ != nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001057 ss_->Remove(this);
1058 WSACloseEvent(hev_);
deadbeef37f5ecf2017-02-27 14:06:41 -08001059 hev_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001060 }
1061 }
1062
1063 virtual void Signal() {
deadbeef37f5ecf2017-02-27 14:06:41 -08001064 if (hev_ != nullptr)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001065 WSASetEvent(hev_);
1066 }
1067
Peter Boström0c4e06b2015-10-07 12:23:21 +02001068 virtual uint32_t GetRequestedEvents() { return 0; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001069
Peter Boström0c4e06b2015-10-07 12:23:21 +02001070 virtual void OnPreEvent(uint32_t ff) { WSAResetEvent(hev_); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001071
Peter Boström0c4e06b2015-10-07 12:23:21 +02001072 virtual void OnEvent(uint32_t ff, int err) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001073
1074 virtual WSAEVENT GetWSAEvent() {
1075 return hev_;
1076 }
1077
1078 virtual SOCKET GetSocket() {
1079 return INVALID_SOCKET;
1080 }
1081
1082 virtual bool CheckSignalClose() { return false; }
1083
1084private:
1085 PhysicalSocketServer* ss_;
1086 WSAEVENT hev_;
1087};
honghaizcec0a082016-01-15 14:49:09 -08001088#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001089
1090// Sets the value of a boolean value to false when signaled.
1091class Signaler : public EventDispatcher {
1092 public:
1093 Signaler(PhysicalSocketServer* ss, bool* pf)
1094 : EventDispatcher(ss), pf_(pf) {
1095 }
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001096 ~Signaler() override { }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001097
Peter Boström0c4e06b2015-10-07 12:23:21 +02001098 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001099 if (pf_)
1100 *pf_ = false;
1101 }
1102
1103 private:
1104 bool *pf_;
1105};
1106
1107PhysicalSocketServer::PhysicalSocketServer()
1108 : fWait_(false) {
1109 signal_wakeup_ = new Signaler(this, &fWait_);
1110#if defined(WEBRTC_WIN)
1111 socket_ev_ = WSACreateEvent();
1112#endif
1113}
1114
1115PhysicalSocketServer::~PhysicalSocketServer() {
1116#if defined(WEBRTC_WIN)
1117 WSACloseEvent(socket_ev_);
1118#endif
1119#if defined(WEBRTC_POSIX)
1120 signal_dispatcher_.reset();
1121#endif
1122 delete signal_wakeup_;
nisseede5da42017-01-12 05:15:36 -08001123 RTC_DCHECK(dispatchers_.empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001124}
1125
1126void PhysicalSocketServer::WakeUp() {
1127 signal_wakeup_->Signal();
1128}
1129
1130Socket* PhysicalSocketServer::CreateSocket(int type) {
1131 return CreateSocket(AF_INET, type);
1132}
1133
1134Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
1135 PhysicalSocket* socket = new PhysicalSocket(this);
1136 if (socket->Create(family, type)) {
1137 return socket;
1138 } else {
1139 delete socket;
jbauch095ae152015-12-18 01:39:55 -08001140 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001141 }
1142}
1143
1144AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int type) {
1145 return CreateAsyncSocket(AF_INET, type);
1146}
1147
1148AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
1149 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1150 if (dispatcher->Create(family, type)) {
1151 return dispatcher;
1152 } else {
1153 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001154 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001155 }
1156}
1157
1158AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
1159 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1160 if (dispatcher->Initialize()) {
1161 return dispatcher;
1162 } else {
1163 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001164 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001165 }
1166}
1167
1168void PhysicalSocketServer::Add(Dispatcher *pdispatcher) {
1169 CritScope cs(&crit_);
1170 // Prevent duplicates. This can cause dead dispatchers to stick around.
1171 DispatcherList::iterator pos = std::find(dispatchers_.begin(),
1172 dispatchers_.end(),
1173 pdispatcher);
1174 if (pos != dispatchers_.end())
1175 return;
1176 dispatchers_.push_back(pdispatcher);
1177}
1178
1179void PhysicalSocketServer::Remove(Dispatcher *pdispatcher) {
1180 CritScope cs(&crit_);
1181 DispatcherList::iterator pos = std::find(dispatchers_.begin(),
1182 dispatchers_.end(),
1183 pdispatcher);
1184 // We silently ignore duplicate calls to Add, so we should silently ignore
1185 // the (expected) symmetric calls to Remove. Note that this may still hide
1186 // a real issue, so we at least log a warning about it.
1187 if (pos == dispatchers_.end()) {
1188 LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
1189 << "dispatcher, potentially from a duplicate call to Add.";
1190 return;
1191 }
1192 size_t index = pos - dispatchers_.begin();
1193 dispatchers_.erase(pos);
1194 for (IteratorList::iterator it = iterators_.begin(); it != iterators_.end();
1195 ++it) {
1196 if (index < **it) {
1197 --**it;
1198 }
1199 }
1200}
1201
1202#if defined(WEBRTC_POSIX)
1203bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
1204 // Calculate timing information
1205
deadbeef37f5ecf2017-02-27 14:06:41 -08001206 struct timeval* ptvWait = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001207 struct timeval tvWait;
1208 struct timeval tvStop;
1209 if (cmsWait != kForever) {
1210 // Calculate wait timeval
1211 tvWait.tv_sec = cmsWait / 1000;
1212 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1213 ptvWait = &tvWait;
1214
1215 // Calculate when to return in a timeval
deadbeef37f5ecf2017-02-27 14:06:41 -08001216 gettimeofday(&tvStop, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001217 tvStop.tv_sec += tvWait.tv_sec;
1218 tvStop.tv_usec += tvWait.tv_usec;
1219 if (tvStop.tv_usec >= 1000000) {
1220 tvStop.tv_usec -= 1000000;
1221 tvStop.tv_sec += 1;
1222 }
1223 }
1224
1225 // Zero all fd_sets. Don't need to do this inside the loop since
1226 // select() zeros the descriptors not signaled
1227
1228 fd_set fdsRead;
1229 FD_ZERO(&fdsRead);
1230 fd_set fdsWrite;
1231 FD_ZERO(&fdsWrite);
pbos@webrtc.org27e58982014-10-07 17:56:53 +00001232 // Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1233 // inline assembly in FD_ZERO.
1234 // http://crbug.com/344505
1235#ifdef MEMORY_SANITIZER
1236 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1237 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1238#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001239
1240 fWait_ = true;
1241
1242 while (fWait_) {
1243 int fdmax = -1;
1244 {
1245 CritScope cr(&crit_);
1246 for (size_t i = 0; i < dispatchers_.size(); ++i) {
1247 // Query dispatchers for read and write wait state
1248 Dispatcher *pdispatcher = dispatchers_[i];
nisseede5da42017-01-12 05:15:36 -08001249 RTC_DCHECK(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001250 if (!process_io && (pdispatcher != signal_wakeup_))
1251 continue;
1252 int fd = pdispatcher->GetDescriptor();
1253 if (fd > fdmax)
1254 fdmax = fd;
1255
Peter Boström0c4e06b2015-10-07 12:23:21 +02001256 uint32_t ff = pdispatcher->GetRequestedEvents();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001257 if (ff & (DE_READ | DE_ACCEPT))
1258 FD_SET(fd, &fdsRead);
1259 if (ff & (DE_WRITE | DE_CONNECT))
1260 FD_SET(fd, &fdsWrite);
1261 }
1262 }
1263
1264 // Wait then call handlers as appropriate
1265 // < 0 means error
1266 // 0 means timeout
1267 // > 0 means count of descriptors ready
deadbeef37f5ecf2017-02-27 14:06:41 -08001268 int n = select(fdmax + 1, &fdsRead, &fdsWrite, nullptr, ptvWait);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001269
1270 // If error, return error.
1271 if (n < 0) {
1272 if (errno != EINTR) {
1273 LOG_E(LS_ERROR, EN, errno) << "select";
1274 return false;
1275 }
1276 // Else ignore the error and keep going. If this EINTR was for one of the
1277 // signals managed by this PhysicalSocketServer, the
1278 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1279 // iteration.
1280 } else if (n == 0) {
1281 // If timeout, return success
1282 return true;
1283 } else {
1284 // We have signaled descriptors
1285 CritScope cr(&crit_);
1286 for (size_t i = 0; i < dispatchers_.size(); ++i) {
1287 Dispatcher *pdispatcher = dispatchers_[i];
1288 int fd = pdispatcher->GetDescriptor();
Peter Boström0c4e06b2015-10-07 12:23:21 +02001289 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001290 int errcode = 0;
1291
1292 // Reap any error code, which can be signaled through reads or writes.
jbauch095ae152015-12-18 01:39:55 -08001293 // TODO(pthatcher): Should we set errcode if getsockopt fails?
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001294 if (FD_ISSET(fd, &fdsRead) || FD_ISSET(fd, &fdsWrite)) {
1295 socklen_t len = sizeof(errcode);
1296 ::getsockopt(fd, SOL_SOCKET, SO_ERROR, &errcode, &len);
1297 }
1298
1299 // Check readable descriptors. If we're waiting on an accept, signal
1300 // that. Otherwise we're waiting for data, check to see if we're
1301 // readable or really closed.
jbauch095ae152015-12-18 01:39:55 -08001302 // TODO(pthatcher): Only peek at TCP descriptors.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001303 if (FD_ISSET(fd, &fdsRead)) {
1304 FD_CLR(fd, &fdsRead);
1305 if (pdispatcher->GetRequestedEvents() & DE_ACCEPT) {
1306 ff |= DE_ACCEPT;
1307 } else if (errcode || pdispatcher->IsDescriptorClosed()) {
1308 ff |= DE_CLOSE;
1309 } else {
1310 ff |= DE_READ;
1311 }
1312 }
1313
1314 // Check writable descriptors. If we're waiting on a connect, detect
1315 // success versus failure by the reaped error code.
1316 if (FD_ISSET(fd, &fdsWrite)) {
1317 FD_CLR(fd, &fdsWrite);
1318 if (pdispatcher->GetRequestedEvents() & DE_CONNECT) {
1319 if (!errcode) {
1320 ff |= DE_CONNECT;
1321 } else {
1322 ff |= DE_CLOSE;
1323 }
1324 } else {
1325 ff |= DE_WRITE;
1326 }
1327 }
1328
1329 // Tell the descriptor about the event.
1330 if (ff != 0) {
1331 pdispatcher->OnPreEvent(ff);
1332 pdispatcher->OnEvent(ff, errcode);
1333 }
1334 }
1335 }
1336
1337 // Recalc the time remaining to wait. Doing it here means it doesn't get
1338 // calced twice the first time through the loop
1339 if (ptvWait) {
1340 ptvWait->tv_sec = 0;
1341 ptvWait->tv_usec = 0;
1342 struct timeval tvT;
deadbeef37f5ecf2017-02-27 14:06:41 -08001343 gettimeofday(&tvT, nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001344 if ((tvStop.tv_sec > tvT.tv_sec)
1345 || ((tvStop.tv_sec == tvT.tv_sec)
1346 && (tvStop.tv_usec > tvT.tv_usec))) {
1347 ptvWait->tv_sec = tvStop.tv_sec - tvT.tv_sec;
1348 ptvWait->tv_usec = tvStop.tv_usec - tvT.tv_usec;
1349 if (ptvWait->tv_usec < 0) {
nisseede5da42017-01-12 05:15:36 -08001350 RTC_DCHECK(ptvWait->tv_sec > 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001351 ptvWait->tv_usec += 1000000;
1352 ptvWait->tv_sec -= 1;
1353 }
1354 }
1355 }
1356 }
1357
1358 return true;
1359}
1360
1361static void GlobalSignalHandler(int signum) {
1362 PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
1363}
1364
1365bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
1366 void (*handler)(int)) {
1367 // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
1368 // otherwise set one.
1369 if (handler == SIG_IGN || handler == SIG_DFL) {
1370 if (!InstallSignal(signum, handler)) {
1371 return false;
1372 }
1373 if (signal_dispatcher_) {
1374 signal_dispatcher_->ClearHandler(signum);
1375 if (!signal_dispatcher_->HasHandlers()) {
1376 signal_dispatcher_.reset();
1377 }
1378 }
1379 } else {
1380 if (!signal_dispatcher_) {
1381 signal_dispatcher_.reset(new PosixSignalDispatcher(this));
1382 }
1383 signal_dispatcher_->SetHandler(signum, handler);
1384 if (!InstallSignal(signum, &GlobalSignalHandler)) {
1385 return false;
1386 }
1387 }
1388 return true;
1389}
1390
1391Dispatcher* PhysicalSocketServer::signal_dispatcher() {
1392 return signal_dispatcher_.get();
1393}
1394
1395bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
1396 struct sigaction act;
1397 // It doesn't really matter what we set this mask to.
1398 if (sigemptyset(&act.sa_mask) != 0) {
1399 LOG_ERR(LS_ERROR) << "Couldn't set mask";
1400 return false;
1401 }
1402 act.sa_handler = handler;
1403#if !defined(__native_client__)
1404 // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
1405 // and it's a nuisance. Though some syscalls still return EINTR and there's no
1406 // real standard for which ones. :(
1407 act.sa_flags = SA_RESTART;
1408#else
1409 act.sa_flags = 0;
1410#endif
deadbeef37f5ecf2017-02-27 14:06:41 -08001411 if (sigaction(signum, &act, nullptr) != 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001412 LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
1413 return false;
1414 }
1415 return true;
1416}
1417#endif // WEBRTC_POSIX
1418
1419#if defined(WEBRTC_WIN)
1420bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
Honghai Zhang82d78622016-05-06 11:29:15 -07001421 int64_t cmsTotal = cmsWait;
1422 int64_t cmsElapsed = 0;
1423 int64_t msStart = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001424
1425 fWait_ = true;
1426 while (fWait_) {
1427 std::vector<WSAEVENT> events;
1428 std::vector<Dispatcher *> event_owners;
1429
1430 events.push_back(socket_ev_);
1431
1432 {
1433 CritScope cr(&crit_);
1434 size_t i = 0;
1435 iterators_.push_back(&i);
1436 // Don't track dispatchers_.size(), because we want to pick up any new
1437 // dispatchers that were added while processing the loop.
1438 while (i < dispatchers_.size()) {
1439 Dispatcher* disp = dispatchers_[i++];
1440 if (!process_io && (disp != signal_wakeup_))
1441 continue;
1442 SOCKET s = disp->GetSocket();
1443 if (disp->CheckSignalClose()) {
1444 // We just signalled close, don't poll this socket
1445 } else if (s != INVALID_SOCKET) {
1446 WSAEventSelect(s,
1447 events[0],
1448 FlagsToEvents(disp->GetRequestedEvents()));
1449 } else {
1450 events.push_back(disp->GetWSAEvent());
1451 event_owners.push_back(disp);
1452 }
1453 }
nisseede5da42017-01-12 05:15:36 -08001454 RTC_DCHECK(iterators_.back() == &i);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001455 iterators_.pop_back();
1456 }
1457
1458 // Which is shorter, the delay wait or the asked wait?
1459
Honghai Zhang82d78622016-05-06 11:29:15 -07001460 int64_t cmsNext;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001461 if (cmsWait == kForever) {
1462 cmsNext = cmsWait;
1463 } else {
Honghai Zhang82d78622016-05-06 11:29:15 -07001464 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001465 }
1466
1467 // Wait for one of the events to signal
1468 DWORD dw = WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()),
1469 &events[0],
1470 false,
Honghai Zhang82d78622016-05-06 11:29:15 -07001471 static_cast<DWORD>(cmsNext),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001472 false);
1473
1474 if (dw == WSA_WAIT_FAILED) {
1475 // Failed?
jbauch095ae152015-12-18 01:39:55 -08001476 // TODO(pthatcher): need a better strategy than this!
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001477 WSAGetLastError();
nissec80e7412017-01-11 05:56:46 -08001478 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001479 return false;
1480 } else if (dw == WSA_WAIT_TIMEOUT) {
1481 // Timeout?
1482 return true;
1483 } else {
1484 // Figure out which one it is and call it
1485 CritScope cr(&crit_);
1486 int index = dw - WSA_WAIT_EVENT_0;
1487 if (index > 0) {
1488 --index; // The first event is the socket event
1489 event_owners[index]->OnPreEvent(0);
1490 event_owners[index]->OnEvent(0, 0);
1491 } else if (process_io) {
1492 size_t i = 0, end = dispatchers_.size();
1493 iterators_.push_back(&i);
1494 iterators_.push_back(&end); // Don't iterate over new dispatchers.
1495 while (i < end) {
1496 Dispatcher* disp = dispatchers_[i++];
1497 SOCKET s = disp->GetSocket();
1498 if (s == INVALID_SOCKET)
1499 continue;
1500
1501 WSANETWORKEVENTS wsaEvents;
1502 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1503 if (err == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001504 {
1505 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1506 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
1507 LOG(WARNING) << "PhysicalSocketServer got FD_READ_BIT error "
1508 << wsaEvents.iErrorCode[FD_READ_BIT];
1509 }
1510 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1511 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
1512 LOG(WARNING) << "PhysicalSocketServer got FD_WRITE_BIT error "
1513 << wsaEvents.iErrorCode[FD_WRITE_BIT];
1514 }
1515 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1516 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
1517 LOG(WARNING) << "PhysicalSocketServer got FD_CONNECT_BIT error "
1518 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
1519 }
1520 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1521 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
1522 LOG(WARNING) << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1523 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
1524 }
1525 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1526 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
1527 LOG(WARNING) << "PhysicalSocketServer got FD_CLOSE_BIT error "
1528 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
1529 }
1530 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001531 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001532 int errcode = 0;
1533 if (wsaEvents.lNetworkEvents & FD_READ)
1534 ff |= DE_READ;
1535 if (wsaEvents.lNetworkEvents & FD_WRITE)
1536 ff |= DE_WRITE;
1537 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1538 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1539 ff |= DE_CONNECT;
1540 } else {
1541 ff |= DE_CLOSE;
1542 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1543 }
1544 }
1545 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1546 ff |= DE_ACCEPT;
1547 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1548 ff |= DE_CLOSE;
1549 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1550 }
1551 if (ff != 0) {
1552 disp->OnPreEvent(ff);
1553 disp->OnEvent(ff, errcode);
1554 }
1555 }
1556 }
nisseede5da42017-01-12 05:15:36 -08001557 RTC_DCHECK(iterators_.back() == &end);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001558 iterators_.pop_back();
nisseede5da42017-01-12 05:15:36 -08001559 RTC_DCHECK(iterators_.back() == &i);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001560 iterators_.pop_back();
1561 }
1562
1563 // Reset the network event until new activity occurs
1564 WSAResetEvent(socket_ev_);
1565 }
1566
1567 // Break?
1568 if (!fWait_)
1569 break;
1570 cmsElapsed = TimeSince(msStart);
1571 if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
1572 break;
1573 }
1574 }
1575
1576 // Done
1577 return true;
1578}
honghaizcec0a082016-01-15 14:49:09 -08001579#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001580
1581} // namespace rtc