blob: e2ec589eb12d0229febab295fe420472957f3a9b [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/common.h"
47#include "webrtc/base/logging.h"
honghaizcec0a082016-01-15 14:49:09 -080048#include "webrtc/base/networkmonitor.h"
danilchapbebf54c2016-04-28 01:32:48 -070049#include "webrtc/base/nullsocketserver.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000050#include "webrtc/base/timeutils.h"
51#include "webrtc/base/winping.h"
52#include "webrtc/base/win32socketinit.h"
53
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000054#if defined(WEBRTC_POSIX)
55#include <netinet/tcp.h> // for TCP_NODELAY
56#define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h
57typedef void* SockOptArg;
Stefan Holmer9131efd2016-05-23 18:19:26 +020058
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000059#endif // WEBRTC_POSIX
60
Stefan Holmer3ebb3ef2016-05-23 20:26:11 +020061#if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) && !defined(__native_client__)
62
Stefan Holmer9131efd2016-05-23 18:19:26 +020063int64_t GetSocketRecvTimestamp(int socket) {
64 struct timeval tv_ioctl;
65 int ret = ioctl(socket, SIOCGSTAMP, &tv_ioctl);
66 if (ret != 0)
67 return -1;
68 int64_t timestamp =
69 rtc::kNumMicrosecsPerSec * static_cast<int64_t>(tv_ioctl.tv_sec) +
70 static_cast<int64_t>(tv_ioctl.tv_usec);
71 return timestamp;
72}
73
74#else
75
76int64_t GetSocketRecvTimestamp(int socket) {
77 return -1;
78}
79#endif
80
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000081#if defined(WEBRTC_WIN)
82typedef char* SockOptArg;
83#endif
84
85namespace rtc {
86
danilchapbebf54c2016-04-28 01:32:48 -070087std::unique_ptr<SocketServer> SocketServer::CreateDefault() {
88#if defined(__native_client__)
89 return std::unique_ptr<SocketServer>(new rtc::NullSocketServer);
90#else
91 return std::unique_ptr<SocketServer>(new rtc::PhysicalSocketServer);
92#endif
93}
94
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000095#if defined(WEBRTC_WIN)
96// Standard MTUs, from RFC 1191
Peter Boström0c4e06b2015-10-07 12:23:21 +020097const uint16_t PACKET_MAXIMUMS[] = {
98 65535, // Theoretical maximum, Hyperchannel
99 32000, // Nothing
100 17914, // 16Mb IBM Token Ring
101 8166, // IEEE 802.4
102 // 4464, // IEEE 802.5 (4Mb max)
103 4352, // FDDI
104 // 2048, // Wideband Network
105 2002, // IEEE 802.5 (4Mb recommended)
106 // 1536, // Expermental Ethernet Networks
107 // 1500, // Ethernet, Point-to-Point (default)
108 1492, // IEEE 802.3
109 1006, // SLIP, ARPANET
110 // 576, // X.25 Networks
111 // 544, // DEC IP Portal
112 // 512, // NETBIOS
113 508, // IEEE 802/Source-Rt Bridge, ARCNET
114 296, // Point-to-Point (low delay)
115 68, // Official minimum
116 0, // End of list marker
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000117};
118
119static const int IP_HEADER_SIZE = 20u;
120static const int IPV6_HEADER_SIZE = 40u;
121static const int ICMP_HEADER_SIZE = 8u;
122static const int ICMP_PING_TIMEOUT_MILLIS = 10000u;
123#endif
124
jbauch095ae152015-12-18 01:39:55 -0800125PhysicalSocket::PhysicalSocket(PhysicalSocketServer* ss, SOCKET s)
126 : ss_(ss), s_(s), enabled_events_(0), error_(0),
127 state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED),
128 resolver_(nullptr) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000129#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800130 // EnsureWinsockInit() ensures that winsock is initialized. The default
131 // version of this function doesn't do anything because winsock is
132 // initialized by constructor of a static object. If neccessary libjingle
133 // users can link it with a different version of this function by replacing
134 // win32socketinit.cc. See win32socketinit.cc for more details.
135 EnsureWinsockInit();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000136#endif
jbauch095ae152015-12-18 01:39:55 -0800137 if (s_ != INVALID_SOCKET) {
138 enabled_events_ = DE_READ | DE_WRITE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000139
jbauch095ae152015-12-18 01:39:55 -0800140 int type = SOCK_STREAM;
141 socklen_t len = sizeof(type);
142 VERIFY(0 == getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len));
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) {
192 sockaddr_storage addr_storage;
193 size_t len = bind_addr.ToSockAddrStorage(&addr_storage);
194 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
195 int err = ::bind(s_, addr, static_cast<int>(len));
196 UpdateLastError();
tfarinaa41ab932015-10-30 16:08:48 -0700197#if !defined(NDEBUG)
jbauch095ae152015-12-18 01:39:55 -0800198 if (0 == err) {
199 dbg_addr_ = "Bound @ ";
200 dbg_addr_.append(GetLocalAddress().ToString());
201 }
tfarinaa41ab932015-10-30 16:08:48 -0700202#endif
honghaizcec0a082016-01-15 14:49:09 -0800203 if (ss_->network_binder()) {
204 int result =
205 ss_->network_binder()->BindSocketToNetwork(s_, bind_addr.ipaddr());
206 if (result < 0) {
207 LOG(LS_INFO) << "Binding socket to network address "
208 << bind_addr.ipaddr().ToString() << " result " << result;
209 }
210 }
jbauch095ae152015-12-18 01:39:55 -0800211 return err;
212}
213
214int PhysicalSocket::Connect(const SocketAddress& addr) {
215 // TODO(pthatcher): Implicit creation is required to reconnect...
216 // ...but should we make it more explicit?
217 if (state_ != CS_CLOSED) {
218 SetError(EALREADY);
219 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000220 }
jbauch095ae152015-12-18 01:39:55 -0800221 if (addr.IsUnresolvedIP()) {
222 LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
223 resolver_ = new AsyncResolver();
224 resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult);
225 resolver_->Start(addr);
226 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000227 return 0;
228 }
229
jbauch095ae152015-12-18 01:39:55 -0800230 return DoConnect(addr);
231}
232
233int PhysicalSocket::DoConnect(const SocketAddress& connect_addr) {
234 if ((s_ == INVALID_SOCKET) &&
235 !Create(connect_addr.family(), SOCK_STREAM)) {
236 return SOCKET_ERROR;
237 }
238 sockaddr_storage addr_storage;
239 size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
240 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
241 int err = ::connect(s_, addr, static_cast<int>(len));
242 UpdateLastError();
243 if (err == 0) {
244 state_ = CS_CONNECTED;
245 } else if (IsBlockingError(GetError())) {
246 state_ = CS_CONNECTING;
247 enabled_events_ |= DE_CONNECT;
248 } else {
249 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000250 }
251
jbauch095ae152015-12-18 01:39:55 -0800252 enabled_events_ |= DE_READ | DE_WRITE;
253 return 0;
254}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000255
jbauch095ae152015-12-18 01:39:55 -0800256int PhysicalSocket::GetError() const {
257 CritScope cs(&crit_);
258 return error_;
259}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000260
jbauch095ae152015-12-18 01:39:55 -0800261void PhysicalSocket::SetError(int error) {
262 CritScope cs(&crit_);
263 error_ = error;
264}
265
266AsyncSocket::ConnState PhysicalSocket::GetState() const {
267 return state_;
268}
269
270int PhysicalSocket::GetOption(Option opt, int* value) {
271 int slevel;
272 int sopt;
273 if (TranslateOption(opt, &slevel, &sopt) == -1)
274 return -1;
275 socklen_t optlen = sizeof(*value);
276 int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
277 if (ret != -1 && opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000278#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800279 *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000280#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000281 }
jbauch095ae152015-12-18 01:39:55 -0800282 return ret;
283}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000284
jbauch095ae152015-12-18 01:39:55 -0800285int PhysicalSocket::SetOption(Option opt, int value) {
286 int slevel;
287 int sopt;
288 if (TranslateOption(opt, &slevel, &sopt) == -1)
289 return -1;
290 if (opt == OPT_DONTFRAGMENT) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000291#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800292 value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000293#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000294 }
jbauch095ae152015-12-18 01:39:55 -0800295 return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
296}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000297
jbauch095ae152015-12-18 01:39:55 -0800298int PhysicalSocket::Send(const void* pv, size_t cb) {
jbauchf2a2bf42016-02-03 16:45:32 -0800299 int sent = DoSend(s_, reinterpret_cast<const char *>(pv),
300 static_cast<int>(cb),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000301#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800302 // Suppress SIGPIPE. Without this, attempting to send on a socket whose
303 // other end is closed will result in a SIGPIPE signal being raised to
304 // our process, which by default will terminate the process, which we
305 // don't want. By specifying this flag, we'll just get the error EPIPE
306 // instead and can handle the error gracefully.
307 MSG_NOSIGNAL
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000308#else
jbauch095ae152015-12-18 01:39:55 -0800309 0
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000310#endif
jbauch095ae152015-12-18 01:39:55 -0800311 );
312 UpdateLastError();
313 MaybeRemapSendError();
314 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800315 RTC_DCHECK(sent <= static_cast<int>(cb));
jbauchf2a2bf42016-02-03 16:45:32 -0800316 if ((sent > 0 && sent < static_cast<int>(cb)) ||
317 (sent < 0 && IsBlockingError(GetError()))) {
jbauch095ae152015-12-18 01:39:55 -0800318 enabled_events_ |= DE_WRITE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000319 }
jbauch095ae152015-12-18 01:39:55 -0800320 return sent;
321}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000322
jbauch095ae152015-12-18 01:39:55 -0800323int PhysicalSocket::SendTo(const void* buffer,
324 size_t length,
325 const SocketAddress& addr) {
326 sockaddr_storage saddr;
327 size_t len = addr.ToSockAddrStorage(&saddr);
jbauchf2a2bf42016-02-03 16:45:32 -0800328 int sent = DoSendTo(
jbauch095ae152015-12-18 01:39:55 -0800329 s_, static_cast<const char *>(buffer), static_cast<int>(length),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000330#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
jbauch095ae152015-12-18 01:39:55 -0800331 // Suppress SIGPIPE. See above for explanation.
332 MSG_NOSIGNAL,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000333#else
jbauch095ae152015-12-18 01:39:55 -0800334 0,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000335#endif
jbauch095ae152015-12-18 01:39:55 -0800336 reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
337 UpdateLastError();
338 MaybeRemapSendError();
339 // We have seen minidumps where this may be false.
nisseede5da42017-01-12 05:15:36 -0800340 RTC_DCHECK(sent <= static_cast<int>(length));
jbauchf2a2bf42016-02-03 16:45:32 -0800341 if ((sent > 0 && sent < static_cast<int>(length)) ||
342 (sent < 0 && IsBlockingError(GetError()))) {
jbauch095ae152015-12-18 01:39:55 -0800343 enabled_events_ |= DE_WRITE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000344 }
jbauch095ae152015-12-18 01:39:55 -0800345 return sent;
346}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000347
Stefan Holmer9131efd2016-05-23 18:19:26 +0200348int PhysicalSocket::Recv(void* buffer, size_t length, int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800349 int received = ::recv(s_, static_cast<char*>(buffer),
350 static_cast<int>(length), 0);
351 if ((received == 0) && (length != 0)) {
352 // Note: on graceful shutdown, recv can return 0. In this case, we
353 // pretend it is blocking, and then signal close, so that simplifying
354 // assumptions can be made about Recv.
355 LOG(LS_WARNING) << "EOF from socket; deferring close event";
356 // Must turn this back on so that the select() loop will notice the close
357 // event.
358 enabled_events_ |= DE_READ;
359 SetError(EWOULDBLOCK);
360 return SOCKET_ERROR;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000361 }
Stefan Holmer9131efd2016-05-23 18:19:26 +0200362 if (timestamp) {
363 *timestamp = GetSocketRecvTimestamp(s_);
364 }
jbauch095ae152015-12-18 01:39:55 -0800365 UpdateLastError();
366 int error = GetError();
367 bool success = (received >= 0) || IsBlockingError(error);
368 if (udp_ || success) {
369 enabled_events_ |= DE_READ;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000370 }
jbauch095ae152015-12-18 01:39:55 -0800371 if (!success) {
372 LOG_F(LS_VERBOSE) << "Error = " << error;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000373 }
jbauch095ae152015-12-18 01:39:55 -0800374 return received;
375}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000376
jbauch095ae152015-12-18 01:39:55 -0800377int PhysicalSocket::RecvFrom(void* buffer,
378 size_t length,
Stefan Holmer9131efd2016-05-23 18:19:26 +0200379 SocketAddress* out_addr,
380 int64_t* timestamp) {
jbauch095ae152015-12-18 01:39:55 -0800381 sockaddr_storage addr_storage;
382 socklen_t addr_len = sizeof(addr_storage);
383 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
384 int received = ::recvfrom(s_, static_cast<char*>(buffer),
385 static_cast<int>(length), 0, addr, &addr_len);
Stefan Holmer9131efd2016-05-23 18:19:26 +0200386 if (timestamp) {
387 *timestamp = GetSocketRecvTimestamp(s_);
388 }
jbauch095ae152015-12-18 01:39:55 -0800389 UpdateLastError();
390 if ((received >= 0) && (out_addr != nullptr))
391 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
392 int error = GetError();
393 bool success = (received >= 0) || IsBlockingError(error);
394 if (udp_ || success) {
395 enabled_events_ |= DE_READ;
396 }
397 if (!success) {
398 LOG_F(LS_VERBOSE) << "Error = " << error;
399 }
400 return received;
401}
402
403int PhysicalSocket::Listen(int backlog) {
404 int err = ::listen(s_, backlog);
405 UpdateLastError();
406 if (err == 0) {
407 state_ = CS_CONNECTING;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000408 enabled_events_ |= DE_ACCEPT;
jbauch095ae152015-12-18 01:39:55 -0800409#if !defined(NDEBUG)
410 dbg_addr_ = "Listening @ ";
411 dbg_addr_.append(GetLocalAddress().ToString());
412#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000413 }
jbauch095ae152015-12-18 01:39:55 -0800414 return err;
415}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000416
jbauch095ae152015-12-18 01:39:55 -0800417AsyncSocket* PhysicalSocket::Accept(SocketAddress* out_addr) {
418 // Always re-subscribe DE_ACCEPT to make sure new incoming connections will
419 // trigger an event even if DoAccept returns an error here.
420 enabled_events_ |= DE_ACCEPT;
421 sockaddr_storage addr_storage;
422 socklen_t addr_len = sizeof(addr_storage);
423 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
424 SOCKET s = DoAccept(s_, addr, &addr_len);
425 UpdateLastError();
426 if (s == INVALID_SOCKET)
427 return nullptr;
428 if (out_addr != nullptr)
429 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
430 return ss_->WrapSocket(s);
431}
432
433int PhysicalSocket::Close() {
434 if (s_ == INVALID_SOCKET)
435 return 0;
436 int err = ::closesocket(s_);
437 UpdateLastError();
438 s_ = INVALID_SOCKET;
439 state_ = CS_CLOSED;
440 enabled_events_ = 0;
441 if (resolver_) {
442 resolver_->Destroy(false);
443 resolver_ = nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000444 }
jbauch095ae152015-12-18 01:39:55 -0800445 return err;
446}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000447
jbauch095ae152015-12-18 01:39:55 -0800448int PhysicalSocket::EstimateMTU(uint16_t* mtu) {
449 SocketAddress addr = GetRemoteAddress();
450 if (addr.IsAnyIP()) {
451 SetError(ENOTCONN);
452 return -1;
453 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000454
455#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800456 // Gets the interface MTU (TTL=1) for the interface used to reach |addr|.
457 WinPing ping;
458 if (!ping.IsValid()) {
459 SetError(EINVAL); // can't think of a better error ID
460 return -1;
461 }
462 int header_size = ICMP_HEADER_SIZE;
463 if (addr.family() == AF_INET6) {
464 header_size += IPV6_HEADER_SIZE;
465 } else if (addr.family() == AF_INET) {
466 header_size += IP_HEADER_SIZE;
467 }
468
469 for (int level = 0; PACKET_MAXIMUMS[level + 1] > 0; ++level) {
470 int32_t size = PACKET_MAXIMUMS[level] - header_size;
471 WinPing::PingResult result = ping.Ping(addr.ipaddr(), size,
472 ICMP_PING_TIMEOUT_MILLIS,
473 1, false);
474 if (result == WinPing::PING_FAIL) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000475 SetError(EINVAL); // can't think of a better error ID
476 return -1;
jbauch095ae152015-12-18 01:39:55 -0800477 } else if (result != WinPing::PING_TOO_LARGE) {
478 *mtu = PACKET_MAXIMUMS[level];
479 return 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000480 }
jbauch095ae152015-12-18 01:39:55 -0800481 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000482
nissec80e7412017-01-11 05:56:46 -0800483 RTC_NOTREACHED();
jbauch095ae152015-12-18 01:39:55 -0800484 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000485#elif defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800486 // No simple way to do this on Mac OS X.
487 // SIOCGIFMTU would work if we knew which interface would be used, but
488 // figuring that out is pretty complicated. For now we'll return an error
489 // and let the caller pick a default MTU.
490 SetError(EINVAL);
491 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000492#elif defined(WEBRTC_LINUX)
jbauch095ae152015-12-18 01:39:55 -0800493 // Gets the path MTU.
494 int value;
495 socklen_t vlen = sizeof(value);
496 int err = getsockopt(s_, IPPROTO_IP, IP_MTU, &value, &vlen);
497 if (err < 0) {
498 UpdateLastError();
499 return err;
500 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000501
nisseede5da42017-01-12 05:15:36 -0800502 RTC_DCHECK((0 <= value) && (value <= 65536));
jbauch095ae152015-12-18 01:39:55 -0800503 *mtu = value;
504 return 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000505#elif defined(__native_client__)
jbauch095ae152015-12-18 01:39:55 -0800506 // Most socket operations, including this, will fail in NaCl's sandbox.
507 error_ = EACCES;
508 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000509#endif
jbauch095ae152015-12-18 01:39:55 -0800510}
511
jbauch095ae152015-12-18 01:39:55 -0800512SOCKET PhysicalSocket::DoAccept(SOCKET socket,
513 sockaddr* addr,
514 socklen_t* addrlen) {
515 return ::accept(socket, addr, addrlen);
516}
517
jbauchf2a2bf42016-02-03 16:45:32 -0800518int PhysicalSocket::DoSend(SOCKET socket, const char* buf, int len, int flags) {
519 return ::send(socket, buf, len, flags);
520}
521
522int PhysicalSocket::DoSendTo(SOCKET socket,
523 const char* buf,
524 int len,
525 int flags,
526 const struct sockaddr* dest_addr,
527 socklen_t addrlen) {
528 return ::sendto(socket, buf, len, flags, dest_addr, addrlen);
529}
530
jbauch095ae152015-12-18 01:39:55 -0800531void PhysicalSocket::OnResolveResult(AsyncResolverInterface* resolver) {
532 if (resolver != resolver_) {
533 return;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000534 }
535
jbauch095ae152015-12-18 01:39:55 -0800536 int error = resolver_->GetError();
537 if (error == 0) {
538 error = DoConnect(resolver_->address());
539 } else {
540 Close();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000541 }
542
jbauch095ae152015-12-18 01:39:55 -0800543 if (error) {
544 SetError(error);
545 SignalCloseEvent(this, error);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000546 }
jbauch095ae152015-12-18 01:39:55 -0800547}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000548
jbauch095ae152015-12-18 01:39:55 -0800549void PhysicalSocket::UpdateLastError() {
550 SetError(LAST_SYSTEM_ERROR);
551}
552
553void PhysicalSocket::MaybeRemapSendError() {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000554#if defined(WEBRTC_MAC)
jbauch095ae152015-12-18 01:39:55 -0800555 // https://developer.apple.com/library/mac/documentation/Darwin/
556 // Reference/ManPages/man2/sendto.2.html
557 // ENOBUFS - The output queue for a network interface is full.
558 // This generally indicates that the interface has stopped sending,
559 // but may be caused by transient congestion.
560 if (GetError() == ENOBUFS) {
561 SetError(EWOULDBLOCK);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000562 }
jbauch095ae152015-12-18 01:39:55 -0800563#endif
564}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000565
jbauch095ae152015-12-18 01:39:55 -0800566int PhysicalSocket::TranslateOption(Option opt, int* slevel, int* sopt) {
567 switch (opt) {
568 case OPT_DONTFRAGMENT:
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000569#if defined(WEBRTC_WIN)
jbauch095ae152015-12-18 01:39:55 -0800570 *slevel = IPPROTO_IP;
571 *sopt = IP_DONTFRAGMENT;
572 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000573#elif defined(WEBRTC_MAC) || defined(BSD) || defined(__native_client__)
jbauch095ae152015-12-18 01:39:55 -0800574 LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
575 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000576#elif defined(WEBRTC_POSIX)
jbauch095ae152015-12-18 01:39:55 -0800577 *slevel = IPPROTO_IP;
578 *sopt = IP_MTU_DISCOVER;
579 break;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000580#endif
jbauch095ae152015-12-18 01:39:55 -0800581 case OPT_RCVBUF:
582 *slevel = SOL_SOCKET;
583 *sopt = SO_RCVBUF;
584 break;
585 case OPT_SNDBUF:
586 *slevel = SOL_SOCKET;
587 *sopt = SO_SNDBUF;
588 break;
589 case OPT_NODELAY:
590 *slevel = IPPROTO_TCP;
591 *sopt = TCP_NODELAY;
592 break;
593 case OPT_DSCP:
594 LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
595 return -1;
596 case OPT_RTP_SENDTIME_EXTN_ID:
597 return -1; // No logging is necessary as this not a OS socket option.
598 default:
nissec80e7412017-01-11 05:56:46 -0800599 RTC_NOTREACHED();
jbauch095ae152015-12-18 01:39:55 -0800600 return -1;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000601 }
jbauch095ae152015-12-18 01:39:55 -0800602 return 0;
603}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000604
jbauch4331fcd2016-01-06 22:20:28 -0800605SocketDispatcher::SocketDispatcher(PhysicalSocketServer *ss)
606#if defined(WEBRTC_WIN)
607 : PhysicalSocket(ss), id_(0), signal_close_(false)
608#else
609 : PhysicalSocket(ss)
610#endif
611{
612}
613
614SocketDispatcher::SocketDispatcher(SOCKET s, PhysicalSocketServer *ss)
615#if defined(WEBRTC_WIN)
616 : PhysicalSocket(ss, s), id_(0), signal_close_(false)
617#else
618 : PhysicalSocket(ss, s)
619#endif
620{
621}
622
623SocketDispatcher::~SocketDispatcher() {
624 Close();
625}
626
627bool SocketDispatcher::Initialize() {
nisseede5da42017-01-12 05:15:36 -0800628 RTC_DCHECK(s_ != INVALID_SOCKET);
jbauch4331fcd2016-01-06 22:20:28 -0800629 // Must be a non-blocking
630#if defined(WEBRTC_WIN)
631 u_long argp = 1;
632 ioctlsocket(s_, FIONBIO, &argp);
633#elif defined(WEBRTC_POSIX)
634 fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
635#endif
636 ss_->Add(this);
637 return true;
638}
639
640bool SocketDispatcher::Create(int type) {
641 return Create(AF_INET, type);
642}
643
644bool SocketDispatcher::Create(int family, int type) {
645 // Change the socket to be non-blocking.
646 if (!PhysicalSocket::Create(family, type))
647 return false;
648
649 if (!Initialize())
650 return false;
651
652#if defined(WEBRTC_WIN)
653 do { id_ = ++next_id_; } while (id_ == 0);
654#endif
655 return true;
656}
657
658#if defined(WEBRTC_WIN)
659
660WSAEVENT SocketDispatcher::GetWSAEvent() {
661 return WSA_INVALID_EVENT;
662}
663
664SOCKET SocketDispatcher::GetSocket() {
665 return s_;
666}
667
668bool SocketDispatcher::CheckSignalClose() {
669 if (!signal_close_)
670 return false;
671
672 char ch;
673 if (recv(s_, &ch, 1, MSG_PEEK) > 0)
674 return false;
675
676 state_ = CS_CLOSED;
677 signal_close_ = false;
678 SignalCloseEvent(this, signal_err_);
679 return true;
680}
681
682int SocketDispatcher::next_id_ = 0;
683
684#elif defined(WEBRTC_POSIX)
685
686int SocketDispatcher::GetDescriptor() {
687 return s_;
688}
689
690bool SocketDispatcher::IsDescriptorClosed() {
691 // We don't have a reliable way of distinguishing end-of-stream
692 // from readability. So test on each readable call. Is this
693 // inefficient? Probably.
694 char ch;
695 ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
696 if (res > 0) {
697 // Data available, so not closed.
698 return false;
699 } else if (res == 0) {
700 // EOF, so closed.
701 return true;
702 } else { // error
703 switch (errno) {
704 // Returned if we've already closed s_.
705 case EBADF:
706 // Returned during ungraceful peer shutdown.
707 case ECONNRESET:
708 return true;
709 default:
710 // Assume that all other errors are just blocking errors, meaning the
711 // connection is still good but we just can't read from it right now.
712 // This should only happen when connecting (and at most once), because
713 // in all other cases this function is only called if the file
714 // descriptor is already known to be in the readable state. However,
715 // it's not necessary a problem if we spuriously interpret a
716 // "connection lost"-type error as a blocking error, because typically
717 // the next recv() will get EOF, so we'll still eventually notice that
718 // the socket is closed.
719 LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
720 return false;
721 }
722 }
723}
724
725#endif // WEBRTC_POSIX
726
727uint32_t SocketDispatcher::GetRequestedEvents() {
728 return enabled_events_;
729}
730
731void SocketDispatcher::OnPreEvent(uint32_t ff) {
732 if ((ff & DE_CONNECT) != 0)
733 state_ = CS_CONNECTED;
734
735#if defined(WEBRTC_WIN)
736 // We set CS_CLOSED from CheckSignalClose.
737#elif defined(WEBRTC_POSIX)
738 if ((ff & DE_CLOSE) != 0)
739 state_ = CS_CLOSED;
740#endif
741}
742
743#if defined(WEBRTC_WIN)
744
745void SocketDispatcher::OnEvent(uint32_t ff, int err) {
746 int cache_id = id_;
747 // Make sure we deliver connect/accept first. Otherwise, consumers may see
748 // something like a READ followed by a CONNECT, which would be odd.
749 if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
750 if (ff != DE_CONNECT)
751 LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
752 enabled_events_ &= ~DE_CONNECT;
753#if !defined(NDEBUG)
754 dbg_addr_ = "Connected @ ";
755 dbg_addr_.append(GetRemoteAddress().ToString());
756#endif
757 SignalConnectEvent(this);
758 }
759 if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
760 enabled_events_ &= ~DE_ACCEPT;
761 SignalReadEvent(this);
762 }
763 if ((ff & DE_READ) != 0) {
764 enabled_events_ &= ~DE_READ;
765 SignalReadEvent(this);
766 }
767 if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
768 enabled_events_ &= ~DE_WRITE;
769 SignalWriteEvent(this);
770 }
771 if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
772 signal_close_ = true;
773 signal_err_ = err;
774 }
775}
776
777#elif defined(WEBRTC_POSIX)
778
779void SocketDispatcher::OnEvent(uint32_t ff, int err) {
780 // Make sure we deliver connect/accept first. Otherwise, consumers may see
781 // something like a READ followed by a CONNECT, which would be odd.
782 if ((ff & DE_CONNECT) != 0) {
783 enabled_events_ &= ~DE_CONNECT;
784 SignalConnectEvent(this);
785 }
786 if ((ff & DE_ACCEPT) != 0) {
787 enabled_events_ &= ~DE_ACCEPT;
788 SignalReadEvent(this);
789 }
790 if ((ff & DE_READ) != 0) {
791 enabled_events_ &= ~DE_READ;
792 SignalReadEvent(this);
793 }
794 if ((ff & DE_WRITE) != 0) {
795 enabled_events_ &= ~DE_WRITE;
796 SignalWriteEvent(this);
797 }
798 if ((ff & DE_CLOSE) != 0) {
799 // The socket is now dead to us, so stop checking it.
800 enabled_events_ = 0;
801 SignalCloseEvent(this, err);
802 }
803}
804
805#endif // WEBRTC_POSIX
806
807int SocketDispatcher::Close() {
808 if (s_ == INVALID_SOCKET)
809 return 0;
810
811#if defined(WEBRTC_WIN)
812 id_ = 0;
813 signal_close_ = false;
814#endif
815 ss_->Remove(this);
816 return PhysicalSocket::Close();
817}
818
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000819#if defined(WEBRTC_POSIX)
820class EventDispatcher : public Dispatcher {
821 public:
822 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
823 if (pipe(afd_) < 0)
824 LOG(LERROR) << "pipe failed";
825 ss_->Add(this);
826 }
827
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000828 ~EventDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000829 ss_->Remove(this);
830 close(afd_[0]);
831 close(afd_[1]);
832 }
833
834 virtual void Signal() {
835 CritScope cs(&crit_);
836 if (!fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200837 const uint8_t b[1] = {0};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000838 if (VERIFY(1 == write(afd_[1], b, sizeof(b)))) {
839 fSignaled_ = true;
840 }
841 }
842 }
843
Peter Boström0c4e06b2015-10-07 12:23:21 +0200844 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000845
Peter Boström0c4e06b2015-10-07 12:23:21 +0200846 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000847 // It is not possible to perfectly emulate an auto-resetting event with
848 // pipes. This simulates it by resetting before the event is handled.
849
850 CritScope cs(&crit_);
851 if (fSignaled_) {
Peter Boström0c4e06b2015-10-07 12:23:21 +0200852 uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000853 VERIFY(1 == read(afd_[0], b, sizeof(b)));
854 fSignaled_ = false;
855 }
856 }
857
nissec80e7412017-01-11 05:56:46 -0800858 void OnEvent(uint32_t ff, int err) override { RTC_NOTREACHED(); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000859
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000860 int GetDescriptor() override { return afd_[0]; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000861
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000862 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000863
864 private:
865 PhysicalSocketServer *ss_;
866 int afd_[2];
867 bool fSignaled_;
868 CriticalSection crit_;
869};
870
871// These two classes use the self-pipe trick to deliver POSIX signals to our
872// select loop. This is the only safe, reliable, cross-platform way to do
873// non-trivial things with a POSIX signal in an event-driven program (until
874// proper pselect() implementations become ubiquitous).
875
876class PosixSignalHandler {
877 public:
878 // POSIX only specifies 32 signals, but in principle the system might have
879 // more and the programmer might choose to use them, so we size our array
880 // for 128.
881 static const int kNumPosixSignals = 128;
882
883 // There is just a single global instance. (Signal handlers do not get any
884 // sort of user-defined void * parameter, so they can't access anything that
885 // isn't global.)
886 static PosixSignalHandler* Instance() {
Andrew MacDonald469c2c02015-05-22 17:50:26 -0700887 RTC_DEFINE_STATIC_LOCAL(PosixSignalHandler, instance, ());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000888 return &instance;
889 }
890
891 // Returns true if the given signal number is set.
892 bool IsSignalSet(int signum) const {
nisseede5da42017-01-12 05:15:36 -0800893 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800894 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000895 return received_signal_[signum];
896 } else {
897 return false;
898 }
899 }
900
901 // Clears the given signal number.
902 void ClearSignal(int signum) {
nisseede5da42017-01-12 05:15:36 -0800903 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
tfarina5237aaf2015-11-10 23:44:30 -0800904 if (signum < static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000905 received_signal_[signum] = false;
906 }
907 }
908
909 // Returns the file descriptor to monitor for signal events.
910 int GetDescriptor() const {
911 return afd_[0];
912 }
913
914 // This is called directly from our real signal handler, so it must be
915 // signal-handler-safe. That means it cannot assume anything about the
916 // user-level state of the process, since the handler could be executed at any
917 // time on any thread.
918 void OnPosixSignalReceived(int signum) {
tfarina5237aaf2015-11-10 23:44:30 -0800919 if (signum >= static_cast<int>(arraysize(received_signal_))) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000920 // We don't have space in our array for this.
921 return;
922 }
923 // Set a flag saying we've seen this signal.
924 received_signal_[signum] = true;
925 // Notify application code that we got a signal.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200926 const uint8_t b[1] = {0};
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000927 if (-1 == write(afd_[1], b, sizeof(b))) {
928 // Nothing we can do here. If there's an error somehow then there's
929 // nothing we can safely do from a signal handler.
930 // No, we can't even safely log it.
931 // But, we still have to check the return value here. Otherwise,
932 // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
933 return;
934 }
935 }
936
937 private:
938 PosixSignalHandler() {
939 if (pipe(afd_) < 0) {
940 LOG_ERR(LS_ERROR) << "pipe failed";
941 return;
942 }
943 if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
944 LOG_ERR(LS_WARNING) << "fcntl #1 failed";
945 }
946 if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
947 LOG_ERR(LS_WARNING) << "fcntl #2 failed";
948 }
949 memset(const_cast<void *>(static_cast<volatile void *>(received_signal_)),
950 0,
951 sizeof(received_signal_));
952 }
953
954 ~PosixSignalHandler() {
955 int fd1 = afd_[0];
956 int fd2 = afd_[1];
957 // We clobber the stored file descriptor numbers here or else in principle
958 // a signal that happens to be delivered during application termination
959 // could erroneously write a zero byte to an unrelated file handle in
960 // OnPosixSignalReceived() if some other file happens to be opened later
961 // during shutdown and happens to be given the same file descriptor number
962 // as our pipe had. Unfortunately even with this precaution there is still a
963 // race where that could occur if said signal happens to be handled
964 // concurrently with this code and happens to have already read the value of
965 // afd_[1] from memory before we clobber it, but that's unlikely.
966 afd_[0] = -1;
967 afd_[1] = -1;
968 close(fd1);
969 close(fd2);
970 }
971
972 int afd_[2];
973 // These are boolean flags that will be set in our signal handler and read
974 // and cleared from Wait(). There is a race involved in this, but it is
975 // benign. The signal handler sets the flag before signaling the pipe, so
976 // we'll never end up blocking in select() while a flag is still true.
977 // However, if two of the same signal arrive close to each other then it's
978 // possible that the second time the handler may set the flag while it's still
979 // true, meaning that signal will be missed. But the first occurrence of it
980 // will still be handled, so this isn't a problem.
981 // Volatile is not necessary here for correctness, but this data _is_ volatile
982 // so I've marked it as such.
Peter Boström0c4e06b2015-10-07 12:23:21 +0200983 volatile uint8_t received_signal_[kNumPosixSignals];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000984};
985
986class PosixSignalDispatcher : public Dispatcher {
987 public:
988 PosixSignalDispatcher(PhysicalSocketServer *owner) : owner_(owner) {
989 owner_->Add(this);
990 }
991
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +0000992 ~PosixSignalDispatcher() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000993 owner_->Remove(this);
994 }
995
Peter Boström0c4e06b2015-10-07 12:23:21 +0200996 uint32_t GetRequestedEvents() override { return DE_READ; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000997
Peter Boström0c4e06b2015-10-07 12:23:21 +0200998 void OnPreEvent(uint32_t ff) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000999 // Events might get grouped if signals come very fast, so we read out up to
1000 // 16 bytes to make sure we keep the pipe empty.
Peter Boström0c4e06b2015-10-07 12:23:21 +02001001 uint8_t b[16];
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001002 ssize_t ret = read(GetDescriptor(), b, sizeof(b));
1003 if (ret < 0) {
1004 LOG_ERR(LS_WARNING) << "Error in read()";
1005 } else if (ret == 0) {
1006 LOG(LS_WARNING) << "Should have read at least one byte";
1007 }
1008 }
1009
Peter Boström0c4e06b2015-10-07 12:23:21 +02001010 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001011 for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
1012 ++signum) {
1013 if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
1014 PosixSignalHandler::Instance()->ClearSignal(signum);
1015 HandlerMap::iterator i = handlers_.find(signum);
1016 if (i == handlers_.end()) {
1017 // This can happen if a signal is delivered to our process at around
1018 // the same time as we unset our handler for it. It is not an error
1019 // condition, but it's unusual enough to be worth logging.
1020 LOG(LS_INFO) << "Received signal with no handler: " << signum;
1021 } else {
1022 // Otherwise, execute our handler.
1023 (*i->second)(signum);
1024 }
1025 }
1026 }
1027 }
1028
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001029 int GetDescriptor() override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001030 return PosixSignalHandler::Instance()->GetDescriptor();
1031 }
1032
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001033 bool IsDescriptorClosed() override { return false; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001034
1035 void SetHandler(int signum, void (*handler)(int)) {
1036 handlers_[signum] = handler;
1037 }
1038
1039 void ClearHandler(int signum) {
1040 handlers_.erase(signum);
1041 }
1042
1043 bool HasHandlers() {
1044 return !handlers_.empty();
1045 }
1046
1047 private:
1048 typedef std::map<int, void (*)(int)> HandlerMap;
1049
1050 HandlerMap handlers_;
1051 // Our owner.
1052 PhysicalSocketServer *owner_;
1053};
1054
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001055#endif // WEBRTC_POSIX
1056
1057#if defined(WEBRTC_WIN)
Peter Boström0c4e06b2015-10-07 12:23:21 +02001058static uint32_t FlagsToEvents(uint32_t events) {
1059 uint32_t ffFD = FD_CLOSE;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001060 if (events & DE_READ)
1061 ffFD |= FD_READ;
1062 if (events & DE_WRITE)
1063 ffFD |= FD_WRITE;
1064 if (events & DE_CONNECT)
1065 ffFD |= FD_CONNECT;
1066 if (events & DE_ACCEPT)
1067 ffFD |= FD_ACCEPT;
1068 return ffFD;
1069}
1070
1071class EventDispatcher : public Dispatcher {
1072 public:
1073 EventDispatcher(PhysicalSocketServer *ss) : ss_(ss) {
1074 hev_ = WSACreateEvent();
1075 if (hev_) {
1076 ss_->Add(this);
1077 }
1078 }
1079
1080 ~EventDispatcher() {
1081 if (hev_ != NULL) {
1082 ss_->Remove(this);
1083 WSACloseEvent(hev_);
1084 hev_ = NULL;
1085 }
1086 }
1087
1088 virtual void Signal() {
1089 if (hev_ != NULL)
1090 WSASetEvent(hev_);
1091 }
1092
Peter Boström0c4e06b2015-10-07 12:23:21 +02001093 virtual uint32_t GetRequestedEvents() { return 0; }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001094
Peter Boström0c4e06b2015-10-07 12:23:21 +02001095 virtual void OnPreEvent(uint32_t ff) { WSAResetEvent(hev_); }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001096
Peter Boström0c4e06b2015-10-07 12:23:21 +02001097 virtual void OnEvent(uint32_t ff, int err) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001098
1099 virtual WSAEVENT GetWSAEvent() {
1100 return hev_;
1101 }
1102
1103 virtual SOCKET GetSocket() {
1104 return INVALID_SOCKET;
1105 }
1106
1107 virtual bool CheckSignalClose() { return false; }
1108
1109private:
1110 PhysicalSocketServer* ss_;
1111 WSAEVENT hev_;
1112};
honghaizcec0a082016-01-15 14:49:09 -08001113#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001114
1115// Sets the value of a boolean value to false when signaled.
1116class Signaler : public EventDispatcher {
1117 public:
1118 Signaler(PhysicalSocketServer* ss, bool* pf)
1119 : EventDispatcher(ss), pf_(pf) {
1120 }
kwiberg@webrtc.org67186fe2015-03-09 22:21:53 +00001121 ~Signaler() override { }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001122
Peter Boström0c4e06b2015-10-07 12:23:21 +02001123 void OnEvent(uint32_t ff, int err) override {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001124 if (pf_)
1125 *pf_ = false;
1126 }
1127
1128 private:
1129 bool *pf_;
1130};
1131
1132PhysicalSocketServer::PhysicalSocketServer()
1133 : fWait_(false) {
1134 signal_wakeup_ = new Signaler(this, &fWait_);
1135#if defined(WEBRTC_WIN)
1136 socket_ev_ = WSACreateEvent();
1137#endif
1138}
1139
1140PhysicalSocketServer::~PhysicalSocketServer() {
1141#if defined(WEBRTC_WIN)
1142 WSACloseEvent(socket_ev_);
1143#endif
1144#if defined(WEBRTC_POSIX)
1145 signal_dispatcher_.reset();
1146#endif
1147 delete signal_wakeup_;
nisseede5da42017-01-12 05:15:36 -08001148 RTC_DCHECK(dispatchers_.empty());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001149}
1150
1151void PhysicalSocketServer::WakeUp() {
1152 signal_wakeup_->Signal();
1153}
1154
1155Socket* PhysicalSocketServer::CreateSocket(int type) {
1156 return CreateSocket(AF_INET, type);
1157}
1158
1159Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
1160 PhysicalSocket* socket = new PhysicalSocket(this);
1161 if (socket->Create(family, type)) {
1162 return socket;
1163 } else {
1164 delete socket;
jbauch095ae152015-12-18 01:39:55 -08001165 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001166 }
1167}
1168
1169AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int type) {
1170 return CreateAsyncSocket(AF_INET, type);
1171}
1172
1173AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
1174 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1175 if (dispatcher->Create(family, type)) {
1176 return dispatcher;
1177 } else {
1178 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001179 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001180 }
1181}
1182
1183AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
1184 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1185 if (dispatcher->Initialize()) {
1186 return dispatcher;
1187 } else {
1188 delete dispatcher;
jbauch095ae152015-12-18 01:39:55 -08001189 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001190 }
1191}
1192
1193void PhysicalSocketServer::Add(Dispatcher *pdispatcher) {
1194 CritScope cs(&crit_);
1195 // Prevent duplicates. This can cause dead dispatchers to stick around.
1196 DispatcherList::iterator pos = std::find(dispatchers_.begin(),
1197 dispatchers_.end(),
1198 pdispatcher);
1199 if (pos != dispatchers_.end())
1200 return;
1201 dispatchers_.push_back(pdispatcher);
1202}
1203
1204void PhysicalSocketServer::Remove(Dispatcher *pdispatcher) {
1205 CritScope cs(&crit_);
1206 DispatcherList::iterator pos = std::find(dispatchers_.begin(),
1207 dispatchers_.end(),
1208 pdispatcher);
1209 // We silently ignore duplicate calls to Add, so we should silently ignore
1210 // the (expected) symmetric calls to Remove. Note that this may still hide
1211 // a real issue, so we at least log a warning about it.
1212 if (pos == dispatchers_.end()) {
1213 LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
1214 << "dispatcher, potentially from a duplicate call to Add.";
1215 return;
1216 }
1217 size_t index = pos - dispatchers_.begin();
1218 dispatchers_.erase(pos);
1219 for (IteratorList::iterator it = iterators_.begin(); it != iterators_.end();
1220 ++it) {
1221 if (index < **it) {
1222 --**it;
1223 }
1224 }
1225}
1226
1227#if defined(WEBRTC_POSIX)
1228bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
1229 // Calculate timing information
1230
1231 struct timeval *ptvWait = NULL;
1232 struct timeval tvWait;
1233 struct timeval tvStop;
1234 if (cmsWait != kForever) {
1235 // Calculate wait timeval
1236 tvWait.tv_sec = cmsWait / 1000;
1237 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1238 ptvWait = &tvWait;
1239
1240 // Calculate when to return in a timeval
1241 gettimeofday(&tvStop, NULL);
1242 tvStop.tv_sec += tvWait.tv_sec;
1243 tvStop.tv_usec += tvWait.tv_usec;
1244 if (tvStop.tv_usec >= 1000000) {
1245 tvStop.tv_usec -= 1000000;
1246 tvStop.tv_sec += 1;
1247 }
1248 }
1249
1250 // Zero all fd_sets. Don't need to do this inside the loop since
1251 // select() zeros the descriptors not signaled
1252
1253 fd_set fdsRead;
1254 FD_ZERO(&fdsRead);
1255 fd_set fdsWrite;
1256 FD_ZERO(&fdsWrite);
pbos@webrtc.org27e58982014-10-07 17:56:53 +00001257 // Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1258 // inline assembly in FD_ZERO.
1259 // http://crbug.com/344505
1260#ifdef MEMORY_SANITIZER
1261 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1262 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1263#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001264
1265 fWait_ = true;
1266
1267 while (fWait_) {
1268 int fdmax = -1;
1269 {
1270 CritScope cr(&crit_);
1271 for (size_t i = 0; i < dispatchers_.size(); ++i) {
1272 // Query dispatchers for read and write wait state
1273 Dispatcher *pdispatcher = dispatchers_[i];
nisseede5da42017-01-12 05:15:36 -08001274 RTC_DCHECK(pdispatcher);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001275 if (!process_io && (pdispatcher != signal_wakeup_))
1276 continue;
1277 int fd = pdispatcher->GetDescriptor();
1278 if (fd > fdmax)
1279 fdmax = fd;
1280
Peter Boström0c4e06b2015-10-07 12:23:21 +02001281 uint32_t ff = pdispatcher->GetRequestedEvents();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001282 if (ff & (DE_READ | DE_ACCEPT))
1283 FD_SET(fd, &fdsRead);
1284 if (ff & (DE_WRITE | DE_CONNECT))
1285 FD_SET(fd, &fdsWrite);
1286 }
1287 }
1288
1289 // Wait then call handlers as appropriate
1290 // < 0 means error
1291 // 0 means timeout
1292 // > 0 means count of descriptors ready
1293 int n = select(fdmax + 1, &fdsRead, &fdsWrite, NULL, ptvWait);
1294
1295 // If error, return error.
1296 if (n < 0) {
1297 if (errno != EINTR) {
1298 LOG_E(LS_ERROR, EN, errno) << "select";
1299 return false;
1300 }
1301 // Else ignore the error and keep going. If this EINTR was for one of the
1302 // signals managed by this PhysicalSocketServer, the
1303 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1304 // iteration.
1305 } else if (n == 0) {
1306 // If timeout, return success
1307 return true;
1308 } else {
1309 // We have signaled descriptors
1310 CritScope cr(&crit_);
1311 for (size_t i = 0; i < dispatchers_.size(); ++i) {
1312 Dispatcher *pdispatcher = dispatchers_[i];
1313 int fd = pdispatcher->GetDescriptor();
Peter Boström0c4e06b2015-10-07 12:23:21 +02001314 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001315 int errcode = 0;
1316
1317 // Reap any error code, which can be signaled through reads or writes.
jbauch095ae152015-12-18 01:39:55 -08001318 // TODO(pthatcher): Should we set errcode if getsockopt fails?
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001319 if (FD_ISSET(fd, &fdsRead) || FD_ISSET(fd, &fdsWrite)) {
1320 socklen_t len = sizeof(errcode);
1321 ::getsockopt(fd, SOL_SOCKET, SO_ERROR, &errcode, &len);
1322 }
1323
1324 // Check readable descriptors. If we're waiting on an accept, signal
1325 // that. Otherwise we're waiting for data, check to see if we're
1326 // readable or really closed.
jbauch095ae152015-12-18 01:39:55 -08001327 // TODO(pthatcher): Only peek at TCP descriptors.
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001328 if (FD_ISSET(fd, &fdsRead)) {
1329 FD_CLR(fd, &fdsRead);
1330 if (pdispatcher->GetRequestedEvents() & DE_ACCEPT) {
1331 ff |= DE_ACCEPT;
1332 } else if (errcode || pdispatcher->IsDescriptorClosed()) {
1333 ff |= DE_CLOSE;
1334 } else {
1335 ff |= DE_READ;
1336 }
1337 }
1338
1339 // Check writable descriptors. If we're waiting on a connect, detect
1340 // success versus failure by the reaped error code.
1341 if (FD_ISSET(fd, &fdsWrite)) {
1342 FD_CLR(fd, &fdsWrite);
1343 if (pdispatcher->GetRequestedEvents() & DE_CONNECT) {
1344 if (!errcode) {
1345 ff |= DE_CONNECT;
1346 } else {
1347 ff |= DE_CLOSE;
1348 }
1349 } else {
1350 ff |= DE_WRITE;
1351 }
1352 }
1353
1354 // Tell the descriptor about the event.
1355 if (ff != 0) {
1356 pdispatcher->OnPreEvent(ff);
1357 pdispatcher->OnEvent(ff, errcode);
1358 }
1359 }
1360 }
1361
1362 // Recalc the time remaining to wait. Doing it here means it doesn't get
1363 // calced twice the first time through the loop
1364 if (ptvWait) {
1365 ptvWait->tv_sec = 0;
1366 ptvWait->tv_usec = 0;
1367 struct timeval tvT;
1368 gettimeofday(&tvT, NULL);
1369 if ((tvStop.tv_sec > tvT.tv_sec)
1370 || ((tvStop.tv_sec == tvT.tv_sec)
1371 && (tvStop.tv_usec > tvT.tv_usec))) {
1372 ptvWait->tv_sec = tvStop.tv_sec - tvT.tv_sec;
1373 ptvWait->tv_usec = tvStop.tv_usec - tvT.tv_usec;
1374 if (ptvWait->tv_usec < 0) {
nisseede5da42017-01-12 05:15:36 -08001375 RTC_DCHECK(ptvWait->tv_sec > 0);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001376 ptvWait->tv_usec += 1000000;
1377 ptvWait->tv_sec -= 1;
1378 }
1379 }
1380 }
1381 }
1382
1383 return true;
1384}
1385
1386static void GlobalSignalHandler(int signum) {
1387 PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
1388}
1389
1390bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
1391 void (*handler)(int)) {
1392 // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
1393 // otherwise set one.
1394 if (handler == SIG_IGN || handler == SIG_DFL) {
1395 if (!InstallSignal(signum, handler)) {
1396 return false;
1397 }
1398 if (signal_dispatcher_) {
1399 signal_dispatcher_->ClearHandler(signum);
1400 if (!signal_dispatcher_->HasHandlers()) {
1401 signal_dispatcher_.reset();
1402 }
1403 }
1404 } else {
1405 if (!signal_dispatcher_) {
1406 signal_dispatcher_.reset(new PosixSignalDispatcher(this));
1407 }
1408 signal_dispatcher_->SetHandler(signum, handler);
1409 if (!InstallSignal(signum, &GlobalSignalHandler)) {
1410 return false;
1411 }
1412 }
1413 return true;
1414}
1415
1416Dispatcher* PhysicalSocketServer::signal_dispatcher() {
1417 return signal_dispatcher_.get();
1418}
1419
1420bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
1421 struct sigaction act;
1422 // It doesn't really matter what we set this mask to.
1423 if (sigemptyset(&act.sa_mask) != 0) {
1424 LOG_ERR(LS_ERROR) << "Couldn't set mask";
1425 return false;
1426 }
1427 act.sa_handler = handler;
1428#if !defined(__native_client__)
1429 // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
1430 // and it's a nuisance. Though some syscalls still return EINTR and there's no
1431 // real standard for which ones. :(
1432 act.sa_flags = SA_RESTART;
1433#else
1434 act.sa_flags = 0;
1435#endif
1436 if (sigaction(signum, &act, NULL) != 0) {
1437 LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
1438 return false;
1439 }
1440 return true;
1441}
1442#endif // WEBRTC_POSIX
1443
1444#if defined(WEBRTC_WIN)
1445bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
Honghai Zhang82d78622016-05-06 11:29:15 -07001446 int64_t cmsTotal = cmsWait;
1447 int64_t cmsElapsed = 0;
1448 int64_t msStart = Time();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001449
1450 fWait_ = true;
1451 while (fWait_) {
1452 std::vector<WSAEVENT> events;
1453 std::vector<Dispatcher *> event_owners;
1454
1455 events.push_back(socket_ev_);
1456
1457 {
1458 CritScope cr(&crit_);
1459 size_t i = 0;
1460 iterators_.push_back(&i);
1461 // Don't track dispatchers_.size(), because we want to pick up any new
1462 // dispatchers that were added while processing the loop.
1463 while (i < dispatchers_.size()) {
1464 Dispatcher* disp = dispatchers_[i++];
1465 if (!process_io && (disp != signal_wakeup_))
1466 continue;
1467 SOCKET s = disp->GetSocket();
1468 if (disp->CheckSignalClose()) {
1469 // We just signalled close, don't poll this socket
1470 } else if (s != INVALID_SOCKET) {
1471 WSAEventSelect(s,
1472 events[0],
1473 FlagsToEvents(disp->GetRequestedEvents()));
1474 } else {
1475 events.push_back(disp->GetWSAEvent());
1476 event_owners.push_back(disp);
1477 }
1478 }
nisseede5da42017-01-12 05:15:36 -08001479 RTC_DCHECK(iterators_.back() == &i);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001480 iterators_.pop_back();
1481 }
1482
1483 // Which is shorter, the delay wait or the asked wait?
1484
Honghai Zhang82d78622016-05-06 11:29:15 -07001485 int64_t cmsNext;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001486 if (cmsWait == kForever) {
1487 cmsNext = cmsWait;
1488 } else {
Honghai Zhang82d78622016-05-06 11:29:15 -07001489 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001490 }
1491
1492 // Wait for one of the events to signal
1493 DWORD dw = WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()),
1494 &events[0],
1495 false,
Honghai Zhang82d78622016-05-06 11:29:15 -07001496 static_cast<DWORD>(cmsNext),
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001497 false);
1498
1499 if (dw == WSA_WAIT_FAILED) {
1500 // Failed?
jbauch095ae152015-12-18 01:39:55 -08001501 // TODO(pthatcher): need a better strategy than this!
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001502 WSAGetLastError();
nissec80e7412017-01-11 05:56:46 -08001503 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001504 return false;
1505 } else if (dw == WSA_WAIT_TIMEOUT) {
1506 // Timeout?
1507 return true;
1508 } else {
1509 // Figure out which one it is and call it
1510 CritScope cr(&crit_);
1511 int index = dw - WSA_WAIT_EVENT_0;
1512 if (index > 0) {
1513 --index; // The first event is the socket event
1514 event_owners[index]->OnPreEvent(0);
1515 event_owners[index]->OnEvent(0, 0);
1516 } else if (process_io) {
1517 size_t i = 0, end = dispatchers_.size();
1518 iterators_.push_back(&i);
1519 iterators_.push_back(&end); // Don't iterate over new dispatchers.
1520 while (i < end) {
1521 Dispatcher* disp = dispatchers_[i++];
1522 SOCKET s = disp->GetSocket();
1523 if (s == INVALID_SOCKET)
1524 continue;
1525
1526 WSANETWORKEVENTS wsaEvents;
1527 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1528 if (err == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001529 {
1530 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1531 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
1532 LOG(WARNING) << "PhysicalSocketServer got FD_READ_BIT error "
1533 << wsaEvents.iErrorCode[FD_READ_BIT];
1534 }
1535 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1536 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
1537 LOG(WARNING) << "PhysicalSocketServer got FD_WRITE_BIT error "
1538 << wsaEvents.iErrorCode[FD_WRITE_BIT];
1539 }
1540 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1541 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
1542 LOG(WARNING) << "PhysicalSocketServer got FD_CONNECT_BIT error "
1543 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
1544 }
1545 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1546 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
1547 LOG(WARNING) << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1548 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
1549 }
1550 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1551 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
1552 LOG(WARNING) << "PhysicalSocketServer got FD_CLOSE_BIT error "
1553 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
1554 }
1555 }
Peter Boström0c4e06b2015-10-07 12:23:21 +02001556 uint32_t ff = 0;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001557 int errcode = 0;
1558 if (wsaEvents.lNetworkEvents & FD_READ)
1559 ff |= DE_READ;
1560 if (wsaEvents.lNetworkEvents & FD_WRITE)
1561 ff |= DE_WRITE;
1562 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1563 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1564 ff |= DE_CONNECT;
1565 } else {
1566 ff |= DE_CLOSE;
1567 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1568 }
1569 }
1570 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1571 ff |= DE_ACCEPT;
1572 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1573 ff |= DE_CLOSE;
1574 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1575 }
1576 if (ff != 0) {
1577 disp->OnPreEvent(ff);
1578 disp->OnEvent(ff, errcode);
1579 }
1580 }
1581 }
nisseede5da42017-01-12 05:15:36 -08001582 RTC_DCHECK(iterators_.back() == &end);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001583 iterators_.pop_back();
nisseede5da42017-01-12 05:15:36 -08001584 RTC_DCHECK(iterators_.back() == &i);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001585 iterators_.pop_back();
1586 }
1587
1588 // Reset the network event until new activity occurs
1589 WSAResetEvent(socket_ev_);
1590 }
1591
1592 // Break?
1593 if (!fWait_)
1594 break;
1595 cmsElapsed = TimeSince(msStart);
1596 if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
1597 break;
1598 }
1599 }
1600
1601 // Done
1602 return true;
1603}
honghaizcec0a082016-01-15 14:49:09 -08001604#endif // WEBRTC_WIN
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001605
1606} // namespace rtc