1 /*
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 */
10 #include "rtc_base/physicalsocketserver.h"
11
12 #if defined(_MSC_VER) && _MSC_VER < 1300
13 #pragma warning(disable:4786)
14 #endif
15
16 #ifdef MEMORY_SANITIZER
17 #include <sanitizer/msan_interface.h>
18 #endif
19
20 #if defined(WEBRTC_POSIX)
21 #include <string.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #if defined(WEBRTC_USE_EPOLL)
25 // "poll" will be used to wait for the signal dispatcher.
26 #include <poll.h>
27 #endif
28 #include <sys/ioctl.h>
29 #include <sys/time.h>
30 #include <sys/select.h>
31 #include <unistd.h>
32 #include <signal.h>
33 #endif
34
35 #if defined(WEBRTC_WIN)
36 #define WIN32_LEAN_AND_MEAN
37 #include <windows.h>
38 #include <winsock2.h>
39 #include <ws2tcpip.h>
40 #undef SetPort
41 #endif
42
43 #include <algorithm>
44 #include <map>
45
46 #include "rtc_base/arraysize.h"
47 #include "rtc_base/basictypes.h"
48 #include "rtc_base/byteorder.h"
49 #include "rtc_base/checks.h"
50 #include "rtc_base/logging.h"
51 #include "rtc_base/networkmonitor.h"
52 #include "rtc_base/nullsocketserver.h"
53 #include "rtc_base/timeutils.h"
54 #include "rtc_base/win32socketinit.h"
55
56 #if defined(WEBRTC_POSIX)
57 #include <netinet/tcp.h> // for TCP_NODELAY
58 #define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h
59 typedef void* SockOptArg;
60
61 #endif // WEBRTC_POSIX
62
63 #if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) && !defined(WEBRTC_BSD) && !defined(__native_client__)
64 #if defined(WEBRTC_LINUX)
65 #include <linux/sockios.h>
66 #endif
67
GetSocketRecvTimestamp(int socket)68 int64_t GetSocketRecvTimestamp(int socket) {
69 struct timeval tv_ioctl;
70 int ret = ioctl(socket, SIOCGSTAMP, &tv_ioctl);
71 if (ret != 0)
72 return -1;
73 int64_t timestamp =
74 rtc::kNumMicrosecsPerSec * static_cast<int64_t>(tv_ioctl.tv_sec) +
75 static_cast<int64_t>(tv_ioctl.tv_usec);
76 return timestamp;
77 }
78
79 #else
80
GetSocketRecvTimestamp(int socket)81 int64_t GetSocketRecvTimestamp(int socket) {
82 return -1;
83 }
84 #endif
85
86 #if defined(WEBRTC_WIN)
87 typedef char* SockOptArg;
88 #endif
89
90 #if defined(WEBRTC_USE_EPOLL)
91 // POLLRDHUP / EPOLLRDHUP are only defined starting with Linux 2.6.17.
92 #if !defined(POLLRDHUP)
93 #define POLLRDHUP 0x2000
94 #endif
95 #if !defined(EPOLLRDHUP)
96 #define EPOLLRDHUP 0x2000
97 #endif
98 #endif
99
100 namespace rtc {
101
CreateDefault()102 std::unique_ptr<SocketServer> SocketServer::CreateDefault() {
103 #if defined(__native_client__)
104 return std::unique_ptr<SocketServer>(new rtc::NullSocketServer);
105 #else
106 return std::unique_ptr<SocketServer>(new rtc::PhysicalSocketServer);
107 #endif
108 }
109
110 #if defined(WEBRTC_WIN)
111 // Standard MTUs, from RFC 1191
112 const uint16_t PACKET_MAXIMUMS[] = {
113 65535, // Theoretical maximum, Hyperchannel
114 32000, // Nothing
115 17914, // 16Mb IBM Token Ring
116 8166, // IEEE 802.4
117 // 4464, // IEEE 802.5 (4Mb max)
118 4352, // FDDI
119 // 2048, // Wideband Network
120 2002, // IEEE 802.5 (4Mb recommended)
121 // 1536, // Expermental Ethernet Networks
122 // 1500, // Ethernet, Point-to-Point (default)
123 1492, // IEEE 802.3
124 1006, // SLIP, ARPANET
125 // 576, // X.25 Networks
126 // 544, // DEC IP Portal
127 // 512, // NETBIOS
128 508, // IEEE 802/Source-Rt Bridge, ARCNET
129 296, // Point-to-Point (low delay)
130 68, // Official minimum
131 0, // End of list marker
132 };
133
134 static const int IP_HEADER_SIZE = 20u;
135 static const int IPV6_HEADER_SIZE = 40u;
136 static const int ICMP_HEADER_SIZE = 8u;
137 static const int ICMP_PING_TIMEOUT_MILLIS = 10000u;
138 #endif
139
PhysicalSocket(PhysicalSocketServer * ss,SOCKET s)140 PhysicalSocket::PhysicalSocket(PhysicalSocketServer* ss, SOCKET s)
141 : ss_(ss), s_(s), error_(0),
142 state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED),
143 resolver_(nullptr) {
144 #if defined(WEBRTC_WIN)
145 // EnsureWinsockInit() ensures that winsock is initialized. The default
146 // version of this function doesn't do anything because winsock is
147 // initialized by constructor of a static object. If neccessary libjingle
148 // users can link it with a different version of this function by replacing
149 // win32socketinit.cc. See win32socketinit.cc for more details.
150 EnsureWinsockInit();
151 #endif
152 if (s_ != INVALID_SOCKET) {
153 SetEnabledEvents(DE_READ | DE_WRITE);
154
155 int type = SOCK_STREAM;
156 socklen_t len = sizeof(type);
157 const int res =
158 getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len);
159 RTC_DCHECK_EQ(0, res);
160 udp_ = (SOCK_DGRAM == type);
161 }
162 }
163
~PhysicalSocket()164 PhysicalSocket::~PhysicalSocket() {
165 Close();
166 }
167
Create(int family,int type)168 bool PhysicalSocket::Create(int family, int type) {
169 Close();
170 s_ = ::socket(family, type, 0);
171 udp_ = (SOCK_DGRAM == type);
172 UpdateLastError();
173 if (udp_) {
174 SetEnabledEvents(DE_READ | DE_WRITE);
175 }
176 return s_ != INVALID_SOCKET;
177 }
178
GetLocalAddress() const179 SocketAddress PhysicalSocket::GetLocalAddress() const {
180 sockaddr_storage addr_storage = {0};
181 socklen_t addrlen = sizeof(addr_storage);
182 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
183 int result = ::getsockname(s_, addr, &addrlen);
184 SocketAddress address;
185 if (result >= 0) {
186 SocketAddressFromSockAddrStorage(addr_storage, &address);
187 } else {
188 RTC_LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
189 << s_;
190 }
191 return address;
192 }
193
GetRemoteAddress() const194 SocketAddress PhysicalSocket::GetRemoteAddress() const {
195 sockaddr_storage addr_storage = {0};
196 socklen_t addrlen = sizeof(addr_storage);
197 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
198 int result = ::getpeername(s_, addr, &addrlen);
199 SocketAddress address;
200 if (result >= 0) {
201 SocketAddressFromSockAddrStorage(addr_storage, &address);
202 } else {
203 RTC_LOG(LS_WARNING)
204 << "GetRemoteAddress: unable to get remote addr, socket=" << s_;
205 }
206 return address;
207 }
208
Bind(const SocketAddress & bind_addr)209 int PhysicalSocket::Bind(const SocketAddress& bind_addr) {
210 SocketAddress copied_bind_addr = bind_addr;
211 // If a network binder is available, use it to bind a socket to an interface
212 // instead of bind(), since this is more reliable on an OS with a weak host
213 // model.
214 if (ss_->network_binder() && !bind_addr.IsAnyIP()) {
215 NetworkBindingResult result =
216 ss_->network_binder()->BindSocketToNetwork(s_, bind_addr.ipaddr());
217 if (result == NetworkBindingResult::SUCCESS) {
218 // Since the network binder handled binding the socket to the desired
219 // network interface, we don't need to (and shouldn't) include an IP in
220 // the bind() call; bind() just needs to assign a port.
221 copied_bind_addr.SetIP(GetAnyIP(copied_bind_addr.ipaddr().family()));
222 } else if (result == NetworkBindingResult::NOT_IMPLEMENTED) {
223 RTC_LOG(LS_INFO) << "Can't bind socket to network because "
224 "network binding is not implemented for this OS.";
225 } else {
226 if (bind_addr.IsLoopbackIP()) {
227 // If we couldn't bind to a loopback IP (which should only happen in
228 // test scenarios), continue on. This may be expected behavior.
229 RTC_LOG(LS_VERBOSE) << "Binding socket to loopback address "
230 << bind_addr.ipaddr().ToString()
231 << " failed; result: " << static_cast<int>(result);
232 } else {
233 RTC_LOG(LS_WARNING) << "Binding socket to network address "
234 << bind_addr.ipaddr().ToString()
235 << " failed; result: " << static_cast<int>(result);
236 // If a network binding was attempted and failed, we should stop here
237 // and not try to use the socket. Otherwise, we may end up sending
238 // packets with an invalid source address.
239 // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=7026
240 return -1;
241 }
242 }
243 }
244 sockaddr_storage addr_storage;
245 size_t len = copied_bind_addr.ToSockAddrStorage(&addr_storage);
246 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
247 int err = ::bind(s_, addr, static_cast<int>(len));
248 UpdateLastError();
249 #if !defined(NDEBUG)
250 if (0 == err) {
251 dbg_addr_ = "Bound @ ";
252 dbg_addr_.append(GetLocalAddress().ToString());
253 }
254 #endif
255 return err;
256 }
257
Connect(const SocketAddress & addr)258 int PhysicalSocket::Connect(const SocketAddress& addr) {
259 // TODO(pthatcher): Implicit creation is required to reconnect...
260 // ...but should we make it more explicit?
261 if (state_ != CS_CLOSED) {
262 SetError(EALREADY);
263 return SOCKET_ERROR;
264 }
265 if (addr.IsUnresolvedIP()) {
266 RTC_LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
267 resolver_ = new AsyncResolver();
268 resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult);
269 resolver_->Start(addr);
270 state_ = CS_CONNECTING;
271 return 0;
272 }
273
274 return DoConnect(addr);
275 }
276
DoConnect(const SocketAddress & connect_addr)277 int PhysicalSocket::DoConnect(const SocketAddress& connect_addr) {
278 if ((s_ == INVALID_SOCKET) &&
279 !Create(connect_addr.family(), SOCK_STREAM)) {
280 return SOCKET_ERROR;
281 }
282 sockaddr_storage addr_storage;
283 size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
284 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
285 int err = ::connect(s_, addr, static_cast<int>(len));
286 UpdateLastError();
287 uint8_t events = DE_READ | DE_WRITE;
288 if (err == 0) {
289 state_ = CS_CONNECTED;
290 } else if (IsBlockingError(GetError())) {
291 state_ = CS_CONNECTING;
292 events |= DE_CONNECT;
293 } else {
294 return SOCKET_ERROR;
295 }
296
297 EnableEvents(events);
298 return 0;
299 }
300
GetError() const301 int PhysicalSocket::GetError() const {
302 CritScope cs(&crit_);
303 return error_;
304 }
305
SetError(int error)306 void PhysicalSocket::SetError(int error) {
307 CritScope cs(&crit_);
308 error_ = error;
309 }
310
GetState() const311 AsyncSocket::ConnState PhysicalSocket::GetState() const {
312 return state_;
313 }
314
GetOption(Option opt,int * value)315 int PhysicalSocket::GetOption(Option opt, int* value) {
316 int slevel;
317 int sopt;
318 if (TranslateOption(opt, &slevel, &sopt) == -1)
319 return -1;
320 socklen_t optlen = sizeof(*value);
321 int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
322 if (ret != -1 && opt == OPT_DONTFRAGMENT) {
323 #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
324 *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
325 #endif
326 }
327 return ret;
328 }
329
SetOption(Option opt,int value)330 int PhysicalSocket::SetOption(Option opt, int value) {
331 int slevel;
332 int sopt;
333 if (TranslateOption(opt, &slevel, &sopt) == -1)
334 return -1;
335 if (opt == OPT_DONTFRAGMENT) {
336 #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
337 value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
338 #endif
339 }
340 return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
341 }
342
Send(const void * pv,size_t cb)343 int PhysicalSocket::Send(const void* pv, size_t cb) {
344 int sent = DoSend(s_, reinterpret_cast<const char *>(pv),
345 static_cast<int>(cb),
346 #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
347 // Suppress SIGPIPE. Without this, attempting to send on a socket whose
348 // other end is closed will result in a SIGPIPE signal being raised to
349 // our process, which by default will terminate the process, which we
350 // don't want. By specifying this flag, we'll just get the error EPIPE
351 // instead and can handle the error gracefully.
352 MSG_NOSIGNAL
353 #else
354 0
355 #endif
356 );
357 UpdateLastError();
358 MaybeRemapSendError();
359 // We have seen minidumps where this may be false.
360 RTC_DCHECK(sent <= static_cast<int>(cb));
361 if ((sent > 0 && sent < static_cast<int>(cb)) ||
362 (sent < 0 && IsBlockingError(GetError()))) {
363 EnableEvents(DE_WRITE);
364 }
365 return sent;
366 }
367
SendTo(const void * buffer,size_t length,const SocketAddress & addr)368 int PhysicalSocket::SendTo(const void* buffer,
369 size_t length,
370 const SocketAddress& addr) {
371 sockaddr_storage saddr;
372 size_t len = addr.ToSockAddrStorage(&saddr);
373 int sent = DoSendTo(
374 s_, static_cast<const char *>(buffer), static_cast<int>(length),
375 #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
376 // Suppress SIGPIPE. See above for explanation.
377 MSG_NOSIGNAL,
378 #else
379 0,
380 #endif
381 reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
382 UpdateLastError();
383 MaybeRemapSendError();
384 // We have seen minidumps where this may be false.
385 RTC_DCHECK(sent <= static_cast<int>(length));
386 if ((sent > 0 && sent < static_cast<int>(length)) ||
387 (sent < 0 && IsBlockingError(GetError()))) {
388 EnableEvents(DE_WRITE);
389 }
390 return sent;
391 }
392
Recv(void * buffer,size_t length,int64_t * timestamp)393 int PhysicalSocket::Recv(void* buffer, size_t length, int64_t* timestamp) {
394 int received = ::recv(s_, static_cast<char*>(buffer),
395 static_cast<int>(length), 0);
396 if ((received == 0) && (length != 0)) {
397 // Note: on graceful shutdown, recv can return 0. In this case, we
398 // pretend it is blocking, and then signal close, so that simplifying
399 // assumptions can be made about Recv.
400 RTC_LOG(LS_WARNING) << "EOF from socket; deferring close event";
401 // Must turn this back on so that the select() loop will notice the close
402 // event.
403 EnableEvents(DE_READ);
404 SetError(EWOULDBLOCK);
405 return SOCKET_ERROR;
406 }
407 if (timestamp) {
408 *timestamp = GetSocketRecvTimestamp(s_);
409 }
410 UpdateLastError();
411 int error = GetError();
412 bool success = (received >= 0) || IsBlockingError(error);
413 if (udp_ || success) {
414 EnableEvents(DE_READ);
415 }
416 if (!success) {
417 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
418 }
419 return received;
420 }
421
RecvFrom(void * buffer,size_t length,SocketAddress * out_addr,int64_t * timestamp)422 int PhysicalSocket::RecvFrom(void* buffer,
423 size_t length,
424 SocketAddress* out_addr,
425 int64_t* timestamp) {
426 sockaddr_storage addr_storage;
427 socklen_t addr_len = sizeof(addr_storage);
428 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
429 int received = ::recvfrom(s_, static_cast<char*>(buffer),
430 static_cast<int>(length), 0, addr, &addr_len);
431 if (timestamp) {
432 *timestamp = GetSocketRecvTimestamp(s_);
433 }
434 UpdateLastError();
435 if ((received >= 0) && (out_addr != nullptr))
436 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
437 int error = GetError();
438 bool success = (received >= 0) || IsBlockingError(error);
439 if (udp_ || success) {
440 EnableEvents(DE_READ);
441 }
442 if (!success) {
443 RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
444 }
445 return received;
446 }
447
Listen(int backlog)448 int PhysicalSocket::Listen(int backlog) {
449 int err = ::listen(s_, backlog);
450 UpdateLastError();
451 if (err == 0) {
452 state_ = CS_CONNECTING;
453 EnableEvents(DE_ACCEPT);
454 #if !defined(NDEBUG)
455 dbg_addr_ = "Listening @ ";
456 dbg_addr_.append(GetLocalAddress().ToString());
457 #endif
458 }
459 return err;
460 }
461
Accept(SocketAddress * out_addr)462 AsyncSocket* PhysicalSocket::Accept(SocketAddress* out_addr) {
463 // Always re-subscribe DE_ACCEPT to make sure new incoming connections will
464 // trigger an event even if DoAccept returns an error here.
465 EnableEvents(DE_ACCEPT);
466 sockaddr_storage addr_storage;
467 socklen_t addr_len = sizeof(addr_storage);
468 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
469 SOCKET s = DoAccept(s_, addr, &addr_len);
470 UpdateLastError();
471 if (s == INVALID_SOCKET)
472 return nullptr;
473 if (out_addr != nullptr)
474 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
475 return ss_->WrapSocket(s);
476 }
477
Close()478 int PhysicalSocket::Close() {
479 if (s_ == INVALID_SOCKET)
480 return 0;
481 int err = ::closesocket(s_);
482 UpdateLastError();
483 s_ = INVALID_SOCKET;
484 state_ = CS_CLOSED;
485 SetEnabledEvents(0);
486 if (resolver_) {
487 resolver_->Destroy(false);
488 resolver_ = nullptr;
489 }
490 return err;
491 }
492
DoAccept(SOCKET socket,sockaddr * addr,socklen_t * addrlen)493 SOCKET PhysicalSocket::DoAccept(SOCKET socket,
494 sockaddr* addr,
495 socklen_t* addrlen) {
496 return ::accept(socket, addr, addrlen);
497 }
498
DoSend(SOCKET socket,const char * buf,int len,int flags)499 int PhysicalSocket::DoSend(SOCKET socket, const char* buf, int len, int flags) {
500 return ::send(socket, buf, len, flags);
501 }
502
DoSendTo(SOCKET socket,const char * buf,int len,int flags,const struct sockaddr * dest_addr,socklen_t addrlen)503 int PhysicalSocket::DoSendTo(SOCKET socket,
504 const char* buf,
505 int len,
506 int flags,
507 const struct sockaddr* dest_addr,
508 socklen_t addrlen) {
509 return ::sendto(socket, buf, len, flags, dest_addr, addrlen);
510 }
511
OnResolveResult(AsyncResolverInterface * resolver)512 void PhysicalSocket::OnResolveResult(AsyncResolverInterface* resolver) {
513 if (resolver != resolver_) {
514 return;
515 }
516
517 int error = resolver_->GetError();
518 if (error == 0) {
519 error = DoConnect(resolver_->address());
520 } else {
521 Close();
522 }
523
524 if (error) {
525 SetError(error);
526 SignalCloseEvent(this, error);
527 }
528 }
529
UpdateLastError()530 void PhysicalSocket::UpdateLastError() {
531 SetError(RTC_LAST_SYSTEM_ERROR);
532 }
533
MaybeRemapSendError()534 void PhysicalSocket::MaybeRemapSendError() {
535 #if defined(WEBRTC_MAC)
536 // https://developer.apple.com/library/mac/documentation/Darwin/
537 // Reference/ManPages/man2/sendto.2.html
538 // ENOBUFS - The output queue for a network interface is full.
539 // This generally indicates that the interface has stopped sending,
540 // but may be caused by transient congestion.
541 if (GetError() == ENOBUFS) {
542 SetError(EWOULDBLOCK);
543 }
544 #endif
545 }
546
SetEnabledEvents(uint8_t events)547 void PhysicalSocket::SetEnabledEvents(uint8_t events) {
548 enabled_events_ = events;
549 }
550
EnableEvents(uint8_t events)551 void PhysicalSocket::EnableEvents(uint8_t events) {
552 enabled_events_ |= events;
553 }
554
DisableEvents(uint8_t events)555 void PhysicalSocket::DisableEvents(uint8_t events) {
556 enabled_events_ &= ~events;
557 }
558
TranslateOption(Option opt,int * slevel,int * sopt)559 int PhysicalSocket::TranslateOption(Option opt, int* slevel, int* sopt) {
560 switch (opt) {
561 case OPT_DONTFRAGMENT:
562 #if defined(WEBRTC_WIN)
563 *slevel = IPPROTO_IP;
564 *sopt = IP_DONTFRAGMENT;
565 break;
566 #elif defined(WEBRTC_MAC) || defined(WEBRTC_BSD) || defined(__native_client__)
567 RTC_LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
568 return -1;
569 #elif defined(WEBRTC_POSIX)
570 *slevel = IPPROTO_IP;
571 *sopt = IP_MTU_DISCOVER;
572 break;
573 #endif
574 case OPT_RCVBUF:
575 *slevel = SOL_SOCKET;
576 *sopt = SO_RCVBUF;
577 break;
578 case OPT_SNDBUF:
579 *slevel = SOL_SOCKET;
580 *sopt = SO_SNDBUF;
581 break;
582 case OPT_NODELAY:
583 *slevel = IPPROTO_TCP;
584 *sopt = TCP_NODELAY;
585 break;
586 case OPT_DSCP:
587 RTC_LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
588 return -1;
589 case OPT_RTP_SENDTIME_EXTN_ID:
590 return -1; // No logging is necessary as this not a OS socket option.
591 default:
592 RTC_NOTREACHED();
593 return -1;
594 }
595 return 0;
596 }
597
SocketDispatcher(PhysicalSocketServer * ss)598 SocketDispatcher::SocketDispatcher(PhysicalSocketServer *ss)
599 #if defined(WEBRTC_WIN)
600 : PhysicalSocket(ss), id_(0), signal_close_(false)
601 #else
602 : PhysicalSocket(ss)
603 #endif
604 {
605 }
606
SocketDispatcher(SOCKET s,PhysicalSocketServer * ss)607 SocketDispatcher::SocketDispatcher(SOCKET s, PhysicalSocketServer *ss)
608 #if defined(WEBRTC_WIN)
609 : PhysicalSocket(ss, s), id_(0), signal_close_(false)
610 #else
611 : PhysicalSocket(ss, s)
612 #endif
613 {
614 }
615
~SocketDispatcher()616 SocketDispatcher::~SocketDispatcher() {
617 Close();
618 }
619
Initialize()620 bool SocketDispatcher::Initialize() {
621 RTC_DCHECK(s_ != INVALID_SOCKET);
622 // Must be a non-blocking
623 #if defined(WEBRTC_WIN)
624 u_long argp = 1;
625 ioctlsocket(s_, FIONBIO, &argp);
626 #elif defined(WEBRTC_POSIX)
627 fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
628 #endif
629 #if defined(WEBRTC_IOS)
630 // iOS may kill sockets when the app is moved to the background
631 // (specifically, if the app doesn't use the "voip" UIBackgroundMode). When
632 // we attempt to write to such a socket, SIGPIPE will be raised, which by
633 // default will terminate the process, which we don't want. By specifying
634 // this socket option, SIGPIPE will be disabled for the socket.
635 int value = 1;
636 ::setsockopt(s_, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value));
637 #endif
638 ss_->Add(this);
639 return true;
640 }
641
Create(int type)642 bool SocketDispatcher::Create(int type) {
643 return Create(AF_INET, type);
644 }
645
Create(int family,int type)646 bool SocketDispatcher::Create(int family, int type) {
647 // Change the socket to be non-blocking.
648 if (!PhysicalSocket::Create(family, type))
649 return false;
650
651 if (!Initialize())
652 return false;
653
654 #if defined(WEBRTC_WIN)
655 do { id_ = ++next_id_; } while (id_ == 0);
656 #endif
657 return true;
658 }
659
660 #if defined(WEBRTC_WIN)
661
GetWSAEvent()662 WSAEVENT SocketDispatcher::GetWSAEvent() {
663 return WSA_INVALID_EVENT;
664 }
665
GetSocket()666 SOCKET SocketDispatcher::GetSocket() {
667 return s_;
668 }
669
CheckSignalClose()670 bool SocketDispatcher::CheckSignalClose() {
671 if (!signal_close_)
672 return false;
673
674 char ch;
675 if (recv(s_, &ch, 1, MSG_PEEK) > 0)
676 return false;
677
678 state_ = CS_CLOSED;
679 signal_close_ = false;
680 SignalCloseEvent(this, signal_err_);
681 return true;
682 }
683
684 int SocketDispatcher::next_id_ = 0;
685
686 #elif defined(WEBRTC_POSIX)
687
GetDescriptor()688 int SocketDispatcher::GetDescriptor() {
689 return s_;
690 }
691
IsDescriptorClosed()692 bool SocketDispatcher::IsDescriptorClosed() {
693 if (udp_) {
694 // The MSG_PEEK trick doesn't work for UDP, since (at least in some
695 // circumstances) it requires reading an entire UDP packet, which would be
696 // bad for performance here. So, just check whether |s_| has been closed,
697 // which should be sufficient.
698 return s_ == INVALID_SOCKET;
699 }
700 // We don't have a reliable way of distinguishing end-of-stream
701 // from readability. So test on each readable call. Is this
702 // inefficient? Probably.
703 char ch;
704 ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
705 if (res > 0) {
706 // Data available, so not closed.
707 return false;
708 } else if (res == 0) {
709 // EOF, so closed.
710 return true;
711 } else { // error
712 switch (errno) {
713 // Returned if we've already closed s_.
714 case EBADF:
715 // Returned during ungraceful peer shutdown.
716 case ECONNRESET:
717 return true;
718 // The normal blocking error; don't log anything.
719 case EWOULDBLOCK:
720 // Interrupted system call.
721 case EINTR:
722 return false;
723 default:
724 // Assume that all other errors are just blocking errors, meaning the
725 // connection is still good but we just can't read from it right now.
726 // This should only happen when connecting (and at most once), because
727 // in all other cases this function is only called if the file
728 // descriptor is already known to be in the readable state. However,
729 // it's not necessary a problem if we spuriously interpret a
730 // "connection lost"-type error as a blocking error, because typically
731 // the next recv() will get EOF, so we'll still eventually notice that
732 // the socket is closed.
733 RTC_LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
734 return false;
735 }
736 }
737 }
738
739 #endif // WEBRTC_POSIX
740
GetRequestedEvents()741 uint32_t SocketDispatcher::GetRequestedEvents() {
742 return enabled_events();
743 }
744
OnPreEvent(uint32_t ff)745 void SocketDispatcher::OnPreEvent(uint32_t ff) {
746 if ((ff & DE_CONNECT) != 0)
747 state_ = CS_CONNECTED;
748
749 #if defined(WEBRTC_WIN)
750 // We set CS_CLOSED from CheckSignalClose.
751 #elif defined(WEBRTC_POSIX)
752 if ((ff & DE_CLOSE) != 0)
753 state_ = CS_CLOSED;
754 #endif
755 }
756
757 #if defined(WEBRTC_WIN)
758
OnEvent(uint32_t ff,int err)759 void SocketDispatcher::OnEvent(uint32_t ff, int err) {
760 int cache_id = id_;
761 // Make sure we deliver connect/accept first. Otherwise, consumers may see
762 // something like a READ followed by a CONNECT, which would be odd.
763 if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
764 if (ff != DE_CONNECT)
765 RTC_LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
766 DisableEvents(DE_CONNECT);
767 #if !defined(NDEBUG)
768 dbg_addr_ = "Connected @ ";
769 dbg_addr_.append(GetRemoteAddress().ToString());
770 #endif
771 SignalConnectEvent(this);
772 }
773 if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
774 DisableEvents(DE_ACCEPT);
775 SignalReadEvent(this);
776 }
777 if ((ff & DE_READ) != 0) {
778 DisableEvents(DE_READ);
779 SignalReadEvent(this);
780 }
781 if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
782 DisableEvents(DE_WRITE);
783 SignalWriteEvent(this);
784 }
785 if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
786 signal_close_ = true;
787 signal_err_ = err;
788 }
789 }
790
791 #elif defined(WEBRTC_POSIX)
792
OnEvent(uint32_t ff,int err)793 void SocketDispatcher::OnEvent(uint32_t ff, int err) {
794 #if defined(WEBRTC_USE_EPOLL)
795 // Remember currently enabled events so we can combine multiple changes
796 // into one update call later.
797 // The signal handlers might re-enable events disabled here, so we can't
798 // keep a list of events to disable at the end of the method. This list
799 // would not be updated with the events enabled by the signal handlers.
800 StartBatchedEventUpdates();
801 #endif
802 // Make sure we deliver connect/accept first. Otherwise, consumers may see
803 // something like a READ followed by a CONNECT, which would be odd.
804 if ((ff & DE_CONNECT) != 0) {
805 DisableEvents(DE_CONNECT);
806 SignalConnectEvent(this);
807 }
808 if ((ff & DE_ACCEPT) != 0) {
809 DisableEvents(DE_ACCEPT);
810 SignalReadEvent(this);
811 }
812 if ((ff & DE_READ) != 0) {
813 DisableEvents(DE_READ);
814 SignalReadEvent(this);
815 }
816 if ((ff & DE_WRITE) != 0) {
817 DisableEvents(DE_WRITE);
818 SignalWriteEvent(this);
819 }
820 if ((ff & DE_CLOSE) != 0) {
821 // The socket is now dead to us, so stop checking it.
822 SetEnabledEvents(0);
823 SignalCloseEvent(this, err);
824 }
825 #if defined(WEBRTC_USE_EPOLL)
826 FinishBatchedEventUpdates();
827 #endif
828 }
829
830 #endif // WEBRTC_POSIX
831
832 #if defined(WEBRTC_USE_EPOLL)
833
GetEpollEvents(uint32_t ff)834 static int GetEpollEvents(uint32_t ff) {
835 int events = 0;
836 if (ff & (DE_READ | DE_ACCEPT)) {
837 events |= EPOLLIN;
838 }
839 if (ff & (DE_WRITE | DE_CONNECT)) {
840 events |= EPOLLOUT;
841 }
842 return events;
843 }
844
StartBatchedEventUpdates()845 void SocketDispatcher::StartBatchedEventUpdates() {
846 RTC_DCHECK_EQ(saved_enabled_events_, -1);
847 saved_enabled_events_ = enabled_events();
848 }
849
FinishBatchedEventUpdates()850 void SocketDispatcher::FinishBatchedEventUpdates() {
851 RTC_DCHECK_NE(saved_enabled_events_, -1);
852 uint8_t old_events = static_cast<uint8_t>(saved_enabled_events_);
853 saved_enabled_events_ = -1;
854 MaybeUpdateDispatcher(old_events);
855 }
856
MaybeUpdateDispatcher(uint8_t old_events)857 void SocketDispatcher::MaybeUpdateDispatcher(uint8_t old_events) {
858 if (GetEpollEvents(enabled_events()) != GetEpollEvents(old_events) &&
859 saved_enabled_events_ == -1) {
860 ss_->Update(this);
861 }
862 }
863
SetEnabledEvents(uint8_t events)864 void SocketDispatcher::SetEnabledEvents(uint8_t events) {
865 uint8_t old_events = enabled_events();
866 PhysicalSocket::SetEnabledEvents(events);
867 MaybeUpdateDispatcher(old_events);
868 }
869
EnableEvents(uint8_t events)870 void SocketDispatcher::EnableEvents(uint8_t events) {
871 uint8_t old_events = enabled_events();
872 PhysicalSocket::EnableEvents(events);
873 MaybeUpdateDispatcher(old_events);
874 }
875
DisableEvents(uint8_t events)876 void SocketDispatcher::DisableEvents(uint8_t events) {
877 uint8_t old_events = enabled_events();
878 PhysicalSocket::DisableEvents(events);
879 MaybeUpdateDispatcher(old_events);
880 }
881
882 #endif // WEBRTC_USE_EPOLL
883
Close()884 int SocketDispatcher::Close() {
885 if (s_ == INVALID_SOCKET)
886 return 0;
887
888 #if defined(WEBRTC_WIN)
889 id_ = 0;
890 signal_close_ = false;
891 #endif
892 ss_->Remove(this);
893 return PhysicalSocket::Close();
894 }
895
896 #if defined(WEBRTC_POSIX)
897 class EventDispatcher : public Dispatcher {
898 public:
EventDispatcher(PhysicalSocketServer * ss)899 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
900 if (pipe(afd_) < 0)
901 RTC_LOG(LERROR) << "pipe failed";
902 ss_->Add(this);
903 }
904
~EventDispatcher()905 ~EventDispatcher() override {
906 ss_->Remove(this);
907 close(afd_[0]);
908 close(afd_[1]);
909 }
910
Signal()911 virtual void Signal() {
912 CritScope cs(&crit_);
913 if (!fSignaled_) {
914 const uint8_t b[1] = {0};
915 const ssize_t res = write(afd_[1], b, sizeof(b));
916 RTC_DCHECK_EQ(1, res);
917 fSignaled_ = true;
918 }
919 }
920
GetRequestedEvents()921 uint32_t GetRequestedEvents() override { return DE_READ; }
922
OnPreEvent(uint32_t ff)923 void OnPreEvent(uint32_t ff) override {
924 // It is not possible to perfectly emulate an auto-resetting event with
925 // pipes. This simulates it by resetting before the event is handled.
926
927 CritScope cs(&crit_);
928 if (fSignaled_) {
929 uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
930 const ssize_t res = read(afd_[0], b, sizeof(b));
931 RTC_DCHECK_EQ(1, res);
932 fSignaled_ = false;
933 }
934 }
935
OnEvent(uint32_t ff,int err)936 void OnEvent(uint32_t ff, int err) override { RTC_NOTREACHED(); }
937
GetDescriptor()938 int GetDescriptor() override { return afd_[0]; }
939
IsDescriptorClosed()940 bool IsDescriptorClosed() override { return false; }
941
942 private:
943 PhysicalSocketServer *ss_;
944 int afd_[2];
945 bool fSignaled_;
946 CriticalSection crit_;
947 };
948
949 // These two classes use the self-pipe trick to deliver POSIX signals to our
950 // select loop. This is the only safe, reliable, cross-platform way to do
951 // non-trivial things with a POSIX signal in an event-driven program (until
952 // proper pselect() implementations become ubiquitous).
953
954 class PosixSignalHandler {
955 public:
956 // POSIX only specifies 32 signals, but in principle the system might have
957 // more and the programmer might choose to use them, so we size our array
958 // for 128.
959 static const int kNumPosixSignals = 128;
960
961 // There is just a single global instance. (Signal handlers do not get any
962 // sort of user-defined void * parameter, so they can't access anything that
963 // isn't global.)
Instance()964 static PosixSignalHandler* Instance() {
965 RTC_DEFINE_STATIC_LOCAL(PosixSignalHandler, instance, ());
966 return &instance;
967 }
968
969 // Returns true if the given signal number is set.
IsSignalSet(int signum) const970 bool IsSignalSet(int signum) const {
971 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
972 if (signum < static_cast<int>(arraysize(received_signal_))) {
973 return received_signal_[signum];
974 } else {
975 return false;
976 }
977 }
978
979 // Clears the given signal number.
ClearSignal(int signum)980 void ClearSignal(int signum) {
981 RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
982 if (signum < static_cast<int>(arraysize(received_signal_))) {
983 received_signal_[signum] = false;
984 }
985 }
986
987 // Returns the file descriptor to monitor for signal events.
GetDescriptor() const988 int GetDescriptor() const {
989 return afd_[0];
990 }
991
992 // This is called directly from our real signal handler, so it must be
993 // signal-handler-safe. That means it cannot assume anything about the
994 // user-level state of the process, since the handler could be executed at any
995 // time on any thread.
OnPosixSignalReceived(int signum)996 void OnPosixSignalReceived(int signum) {
997 if (signum >= static_cast<int>(arraysize(received_signal_))) {
998 // We don't have space in our array for this.
999 return;
1000 }
1001 // Set a flag saying we've seen this signal.
1002 received_signal_[signum] = true;
1003 // Notify application code that we got a signal.
1004 const uint8_t b[1] = {0};
1005 if (-1 == write(afd_[1], b, sizeof(b))) {
1006 // Nothing we can do here. If there's an error somehow then there's
1007 // nothing we can safely do from a signal handler.
1008 // No, we can't even safely log it.
1009 // But, we still have to check the return value here. Otherwise,
1010 // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
1011 return;
1012 }
1013 }
1014
1015 private:
PosixSignalHandler()1016 PosixSignalHandler() {
1017 if (pipe(afd_) < 0) {
1018 RTC_LOG_ERR(LS_ERROR) << "pipe failed";
1019 return;
1020 }
1021 if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
1022 RTC_LOG_ERR(LS_WARNING) << "fcntl #1 failed";
1023 }
1024 if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
1025 RTC_LOG_ERR(LS_WARNING) << "fcntl #2 failed";
1026 }
1027 memset(const_cast<void *>(static_cast<volatile void *>(received_signal_)),
1028 0,
1029 sizeof(received_signal_));
1030 }
1031
~PosixSignalHandler()1032 ~PosixSignalHandler() {
1033 int fd1 = afd_[0];
1034 int fd2 = afd_[1];
1035 // We clobber the stored file descriptor numbers here or else in principle
1036 // a signal that happens to be delivered during application termination
1037 // could erroneously write a zero byte to an unrelated file handle in
1038 // OnPosixSignalReceived() if some other file happens to be opened later
1039 // during shutdown and happens to be given the same file descriptor number
1040 // as our pipe had. Unfortunately even with this precaution there is still a
1041 // race where that could occur if said signal happens to be handled
1042 // concurrently with this code and happens to have already read the value of
1043 // afd_[1] from memory before we clobber it, but that's unlikely.
1044 afd_[0] = -1;
1045 afd_[1] = -1;
1046 close(fd1);
1047 close(fd2);
1048 }
1049
1050 int afd_[2];
1051 // These are boolean flags that will be set in our signal handler and read
1052 // and cleared from Wait(). There is a race involved in this, but it is
1053 // benign. The signal handler sets the flag before signaling the pipe, so
1054 // we'll never end up blocking in select() while a flag is still true.
1055 // However, if two of the same signal arrive close to each other then it's
1056 // possible that the second time the handler may set the flag while it's still
1057 // true, meaning that signal will be missed. But the first occurrence of it
1058 // will still be handled, so this isn't a problem.
1059 // Volatile is not necessary here for correctness, but this data _is_ volatile
1060 // so I've marked it as such.
1061 volatile uint8_t received_signal_[kNumPosixSignals];
1062 };
1063
1064 class PosixSignalDispatcher : public Dispatcher {
1065 public:
PosixSignalDispatcher(PhysicalSocketServer * owner)1066 PosixSignalDispatcher(PhysicalSocketServer *owner) : owner_(owner) {
1067 owner_->Add(this);
1068 }
1069
~PosixSignalDispatcher()1070 ~PosixSignalDispatcher() override {
1071 owner_->Remove(this);
1072 }
1073
GetRequestedEvents()1074 uint32_t GetRequestedEvents() override { return DE_READ; }
1075
OnPreEvent(uint32_t ff)1076 void OnPreEvent(uint32_t ff) override {
1077 // Events might get grouped if signals come very fast, so we read out up to
1078 // 16 bytes to make sure we keep the pipe empty.
1079 uint8_t b[16];
1080 ssize_t ret = read(GetDescriptor(), b, sizeof(b));
1081 if (ret < 0) {
1082 RTC_LOG_ERR(LS_WARNING) << "Error in read()";
1083 } else if (ret == 0) {
1084 RTC_LOG(LS_WARNING) << "Should have read at least one byte";
1085 }
1086 }
1087
OnEvent(uint32_t ff,int err)1088 void OnEvent(uint32_t ff, int err) override {
1089 for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
1090 ++signum) {
1091 if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
1092 PosixSignalHandler::Instance()->ClearSignal(signum);
1093 HandlerMap::iterator i = handlers_.find(signum);
1094 if (i == handlers_.end()) {
1095 // This can happen if a signal is delivered to our process at around
1096 // the same time as we unset our handler for it. It is not an error
1097 // condition, but it's unusual enough to be worth logging.
1098 RTC_LOG(LS_INFO) << "Received signal with no handler: " << signum;
1099 } else {
1100 // Otherwise, execute our handler.
1101 (*i->second)(signum);
1102 }
1103 }
1104 }
1105 }
1106
GetDescriptor()1107 int GetDescriptor() override {
1108 return PosixSignalHandler::Instance()->GetDescriptor();
1109 }
1110
IsDescriptorClosed()1111 bool IsDescriptorClosed() override { return false; }
1112
SetHandler(int signum,void (* handler)(int))1113 void SetHandler(int signum, void (*handler)(int)) {
1114 handlers_[signum] = handler;
1115 }
1116
ClearHandler(int signum)1117 void ClearHandler(int signum) {
1118 handlers_.erase(signum);
1119 }
1120
HasHandlers()1121 bool HasHandlers() {
1122 return !handlers_.empty();
1123 }
1124
1125 private:
1126 typedef std::map<int, void (*)(int)> HandlerMap;
1127
1128 HandlerMap handlers_;
1129 // Our owner.
1130 PhysicalSocketServer *owner_;
1131 };
1132
1133 #endif // WEBRTC_POSIX
1134
1135 #if defined(WEBRTC_WIN)
FlagsToEvents(uint32_t events)1136 static uint32_t FlagsToEvents(uint32_t events) {
1137 uint32_t ffFD = FD_CLOSE;
1138 if (events & DE_READ)
1139 ffFD |= FD_READ;
1140 if (events & DE_WRITE)
1141 ffFD |= FD_WRITE;
1142 if (events & DE_CONNECT)
1143 ffFD |= FD_CONNECT;
1144 if (events & DE_ACCEPT)
1145 ffFD |= FD_ACCEPT;
1146 return ffFD;
1147 }
1148
1149 class EventDispatcher : public Dispatcher {
1150 public:
EventDispatcher(PhysicalSocketServer * ss)1151 EventDispatcher(PhysicalSocketServer *ss) : ss_(ss) {
1152 hev_ = WSACreateEvent();
1153 if (hev_) {
1154 ss_->Add(this);
1155 }
1156 }
1157
~EventDispatcher()1158 ~EventDispatcher() override {
1159 if (hev_ != nullptr) {
1160 ss_->Remove(this);
1161 WSACloseEvent(hev_);
1162 hev_ = nullptr;
1163 }
1164 }
1165
Signal()1166 virtual void Signal() {
1167 if (hev_ != nullptr)
1168 WSASetEvent(hev_);
1169 }
1170
GetRequestedEvents()1171 uint32_t GetRequestedEvents() override { return 0; }
1172
OnPreEvent(uint32_t ff)1173 void OnPreEvent(uint32_t ff) override { WSAResetEvent(hev_); }
1174
OnEvent(uint32_t ff,int err)1175 void OnEvent(uint32_t ff, int err) override {}
1176
GetWSAEvent()1177 WSAEVENT GetWSAEvent() override { return hev_; }
1178
GetSocket()1179 SOCKET GetSocket() override { return INVALID_SOCKET; }
1180
CheckSignalClose()1181 bool CheckSignalClose() override { return false; }
1182
1183 private:
1184 PhysicalSocketServer* ss_;
1185 WSAEVENT hev_;
1186 };
1187 #endif // WEBRTC_WIN
1188
1189 // Sets the value of a boolean value to false when signaled.
1190 class Signaler : public EventDispatcher {
1191 public:
Signaler(PhysicalSocketServer * ss,bool * pf)1192 Signaler(PhysicalSocketServer* ss, bool* pf)
1193 : EventDispatcher(ss), pf_(pf) {
1194 }
~Signaler()1195 ~Signaler() override { }
1196
OnEvent(uint32_t ff,int err)1197 void OnEvent(uint32_t ff, int err) override {
1198 if (pf_)
1199 *pf_ = false;
1200 }
1201
1202 private:
1203 bool *pf_;
1204 };
1205
PhysicalSocketServer()1206 PhysicalSocketServer::PhysicalSocketServer()
1207 : fWait_(false) {
1208 #if defined(WEBRTC_USE_EPOLL)
1209 // Since Linux 2.6.8, the size argument is ignored, but must be greater than
1210 // zero. Before that the size served as hint to the kernel for the amount of
1211 // space to initially allocate in internal data structures.
1212 epoll_fd_ = epoll_create(FD_SETSIZE);
1213 if (epoll_fd_ == -1) {
1214 // Not an error, will fall back to "select" below.
1215 RTC_LOG_E(LS_WARNING, EN, errno) << "epoll_create";
1216 epoll_fd_ = INVALID_SOCKET;
1217 }
1218 #endif
1219 signal_wakeup_ = new Signaler(this, &fWait_);
1220 #if defined(WEBRTC_WIN)
1221 socket_ev_ = WSACreateEvent();
1222 #endif
1223 }
1224
~PhysicalSocketServer()1225 PhysicalSocketServer::~PhysicalSocketServer() {
1226 #if defined(WEBRTC_WIN)
1227 WSACloseEvent(socket_ev_);
1228 #endif
1229 #if defined(WEBRTC_POSIX)
1230 signal_dispatcher_.reset();
1231 #endif
1232 delete signal_wakeup_;
1233 #if defined(WEBRTC_USE_EPOLL)
1234 if (epoll_fd_ != INVALID_SOCKET) {
1235 close(epoll_fd_);
1236 }
1237 #endif
1238 RTC_DCHECK(dispatchers_.empty());
1239 }
1240
WakeUp()1241 void PhysicalSocketServer::WakeUp() {
1242 signal_wakeup_->Signal();
1243 }
1244
CreateSocket(int type)1245 Socket* PhysicalSocketServer::CreateSocket(int type) {
1246 return CreateSocket(AF_INET, type);
1247 }
1248
CreateSocket(int family,int type)1249 Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
1250 PhysicalSocket* socket = new PhysicalSocket(this);
1251 if (socket->Create(family, type)) {
1252 return socket;
1253 } else {
1254 delete socket;
1255 return nullptr;
1256 }
1257 }
1258
CreateAsyncSocket(int type)1259 AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int type) {
1260 return CreateAsyncSocket(AF_INET, type);
1261 }
1262
CreateAsyncSocket(int family,int type)1263 AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
1264 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1265 if (dispatcher->Create(family, type)) {
1266 return dispatcher;
1267 } else {
1268 delete dispatcher;
1269 return nullptr;
1270 }
1271 }
1272
WrapSocket(SOCKET s)1273 AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
1274 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1275 if (dispatcher->Initialize()) {
1276 return dispatcher;
1277 } else {
1278 delete dispatcher;
1279 return nullptr;
1280 }
1281 }
1282
Add(Dispatcher * pdispatcher)1283 void PhysicalSocketServer::Add(Dispatcher *pdispatcher) {
1284 CritScope cs(&crit_);
1285 if (processing_dispatchers_) {
1286 // A dispatcher is being added while a "Wait" call is processing the
1287 // list of socket events.
1288 // Defer adding to "dispatchers_" set until processing is done to avoid
1289 // invalidating the iterator in "Wait".
1290 pending_remove_dispatchers_.erase(pdispatcher);
1291 pending_add_dispatchers_.insert(pdispatcher);
1292 } else {
1293 dispatchers_.insert(pdispatcher);
1294 }
1295 #if defined(WEBRTC_USE_EPOLL)
1296 if (epoll_fd_ != INVALID_SOCKET) {
1297 AddEpoll(pdispatcher);
1298 }
1299 #endif // WEBRTC_USE_EPOLL
1300 }
1301
Remove(Dispatcher * pdispatcher)1302 void PhysicalSocketServer::Remove(Dispatcher *pdispatcher) {
1303 CritScope cs(&crit_);
1304 if (processing_dispatchers_) {
1305 // A dispatcher is being removed while a "Wait" call is processing the
1306 // list of socket events.
1307 // Defer removal from "dispatchers_" set until processing is done to avoid
1308 // invalidating the iterator in "Wait".
1309 if (!pending_add_dispatchers_.erase(pdispatcher) &&
1310 dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1311 RTC_LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
1312 << "dispatcher, potentially from a duplicate call to "
1313 << "Add.";
1314 return;
1315 }
1316
1317 pending_remove_dispatchers_.insert(pdispatcher);
1318 } else if (!dispatchers_.erase(pdispatcher)) {
1319 RTC_LOG(LS_WARNING)
1320 << "PhysicalSocketServer asked to remove a unknown "
1321 << "dispatcher, potentially from a duplicate call to Add.";
1322 return;
1323 }
1324 #if defined(WEBRTC_USE_EPOLL)
1325 if (epoll_fd_ != INVALID_SOCKET) {
1326 RemoveEpoll(pdispatcher);
1327 }
1328 #endif // WEBRTC_USE_EPOLL
1329 }
1330
Update(Dispatcher * pdispatcher)1331 void PhysicalSocketServer::Update(Dispatcher* pdispatcher) {
1332 #if defined(WEBRTC_USE_EPOLL)
1333 if (epoll_fd_ == INVALID_SOCKET) {
1334 return;
1335 }
1336
1337 CritScope cs(&crit_);
1338 if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1339 return;
1340 }
1341
1342 UpdateEpoll(pdispatcher);
1343 #endif
1344 }
1345
AddRemovePendingDispatchers()1346 void PhysicalSocketServer::AddRemovePendingDispatchers() {
1347 if (!pending_add_dispatchers_.empty()) {
1348 for (Dispatcher* pdispatcher : pending_add_dispatchers_) {
1349 dispatchers_.insert(pdispatcher);
1350 }
1351 pending_add_dispatchers_.clear();
1352 }
1353
1354 if (!pending_remove_dispatchers_.empty()) {
1355 for (Dispatcher* pdispatcher : pending_remove_dispatchers_) {
1356 dispatchers_.erase(pdispatcher);
1357 }
1358 pending_remove_dispatchers_.clear();
1359 }
1360 }
1361
1362 #if defined(WEBRTC_POSIX)
1363
Wait(int cmsWait,bool process_io)1364 bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
1365 #if defined(WEBRTC_USE_EPOLL)
1366 // We don't keep a dedicated "epoll" descriptor containing only the non-IO
1367 // (i.e. signaling) dispatcher, so "poll" will be used instead of the default
1368 // "select" to support sockets larger than FD_SETSIZE.
1369 if (!process_io) {
1370 return WaitPoll(cmsWait, signal_wakeup_);
1371 } else if (epoll_fd_ != INVALID_SOCKET) {
1372 return WaitEpoll(cmsWait);
1373 }
1374 #endif
1375 return WaitSelect(cmsWait, process_io);
1376 }
1377
ProcessEvents(Dispatcher * dispatcher,bool readable,bool writable,bool check_error)1378 static void ProcessEvents(Dispatcher* dispatcher,
1379 bool readable,
1380 bool writable,
1381 bool check_error) {
1382 int errcode = 0;
1383 // TODO(pthatcher): Should we set errcode if getsockopt fails?
1384 if (check_error) {
1385 socklen_t len = sizeof(errcode);
1386 ::getsockopt(dispatcher->GetDescriptor(), SOL_SOCKET, SO_ERROR, &errcode,
1387 &len);
1388 }
1389
1390 uint32_t ff = 0;
1391
1392 // Check readable descriptors. If we're waiting on an accept, signal
1393 // that. Otherwise we're waiting for data, check to see if we're
1394 // readable or really closed.
1395 // TODO(pthatcher): Only peek at TCP descriptors.
1396 if (readable) {
1397 if (dispatcher->GetRequestedEvents() & DE_ACCEPT) {
1398 ff |= DE_ACCEPT;
1399 } else if (errcode || dispatcher->IsDescriptorClosed()) {
1400 ff |= DE_CLOSE;
1401 } else {
1402 ff |= DE_READ;
1403 }
1404 }
1405
1406 // Check writable descriptors. If we're waiting on a connect, detect
1407 // success versus failure by the reaped error code.
1408 if (writable) {
1409 if (dispatcher->GetRequestedEvents() & DE_CONNECT) {
1410 if (!errcode) {
1411 ff |= DE_CONNECT;
1412 } else {
1413 ff |= DE_CLOSE;
1414 }
1415 } else {
1416 ff |= DE_WRITE;
1417 }
1418 }
1419
1420 // Tell the descriptor about the event.
1421 if (ff != 0) {
1422 dispatcher->OnPreEvent(ff);
1423 dispatcher->OnEvent(ff, errcode);
1424 }
1425 }
1426
WaitSelect(int cmsWait,bool process_io)1427 bool PhysicalSocketServer::WaitSelect(int cmsWait, bool process_io) {
1428 // Calculate timing information
1429
1430 struct timeval* ptvWait = nullptr;
1431 struct timeval tvWait;
1432 struct timeval tvStop;
1433 if (cmsWait != kForever) {
1434 // Calculate wait timeval
1435 tvWait.tv_sec = cmsWait / 1000;
1436 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1437 ptvWait = &tvWait;
1438
1439 // Calculate when to return in a timeval
1440 gettimeofday(&tvStop, nullptr);
1441 tvStop.tv_sec += tvWait.tv_sec;
1442 tvStop.tv_usec += tvWait.tv_usec;
1443 if (tvStop.tv_usec >= 1000000) {
1444 tvStop.tv_usec -= 1000000;
1445 tvStop.tv_sec += 1;
1446 }
1447 }
1448
1449 // Zero all fd_sets. Don't need to do this inside the loop since
1450 // select() zeros the descriptors not signaled
1451
1452 fd_set fdsRead;
1453 FD_ZERO(&fdsRead);
1454 fd_set fdsWrite;
1455 FD_ZERO(&fdsWrite);
1456 // Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1457 // inline assembly in FD_ZERO.
1458 // http://crbug.com/344505
1459 #ifdef MEMORY_SANITIZER
1460 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1461 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1462 #endif
1463
1464 fWait_ = true;
1465
1466 while (fWait_) {
1467 int fdmax = -1;
1468 {
1469 CritScope cr(&crit_);
1470 // TODO(jbauch): Support re-entrant waiting.
1471 RTC_DCHECK(!processing_dispatchers_);
1472 for (Dispatcher* pdispatcher : dispatchers_) {
1473 // Query dispatchers for read and write wait state
1474 RTC_DCHECK(pdispatcher);
1475 if (!process_io && (pdispatcher != signal_wakeup_))
1476 continue;
1477 int fd = pdispatcher->GetDescriptor();
1478 // "select"ing a file descriptor that is equal to or larger than
1479 // FD_SETSIZE will result in undefined behavior.
1480 RTC_CHECK_LT(fd, FD_SETSIZE);
1481 if (fd > fdmax)
1482 fdmax = fd;
1483
1484 uint32_t ff = pdispatcher->GetRequestedEvents();
1485 if (ff & (DE_READ | DE_ACCEPT))
1486 FD_SET(fd, &fdsRead);
1487 if (ff & (DE_WRITE | DE_CONNECT))
1488 FD_SET(fd, &fdsWrite);
1489 }
1490 }
1491
1492 // Wait then call handlers as appropriate
1493 // < 0 means error
1494 // 0 means timeout
1495 // > 0 means count of descriptors ready
1496 int n = select(fdmax + 1, &fdsRead, &fdsWrite, nullptr, ptvWait);
1497
1498 // If error, return error.
1499 if (n < 0) {
1500 if (errno != EINTR) {
1501 RTC_LOG_E(LS_ERROR, EN, errno) << "select";
1502 return false;
1503 }
1504 // Else ignore the error and keep going. If this EINTR was for one of the
1505 // signals managed by this PhysicalSocketServer, the
1506 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1507 // iteration.
1508 } else if (n == 0) {
1509 // If timeout, return success
1510 return true;
1511 } else {
1512 // We have signaled descriptors
1513 CritScope cr(&crit_);
1514 processing_dispatchers_ = true;
1515 for (Dispatcher* pdispatcher : dispatchers_) {
1516 int fd = pdispatcher->GetDescriptor();
1517
1518 bool readable = FD_ISSET(fd, &fdsRead);
1519 if (readable) {
1520 FD_CLR(fd, &fdsRead);
1521 }
1522
1523 bool writable = FD_ISSET(fd, &fdsWrite);
1524 if (writable) {
1525 FD_CLR(fd, &fdsWrite);
1526 }
1527
1528 // The error code can be signaled through reads or writes.
1529 ProcessEvents(pdispatcher, readable, writable, readable || writable);
1530 }
1531
1532 processing_dispatchers_ = false;
1533 // Process deferred dispatchers that have been added/removed while the
1534 // events were handled above.
1535 AddRemovePendingDispatchers();
1536 }
1537
1538 // Recalc the time remaining to wait. Doing it here means it doesn't get
1539 // calced twice the first time through the loop
1540 if (ptvWait) {
1541 ptvWait->tv_sec = 0;
1542 ptvWait->tv_usec = 0;
1543 struct timeval tvT;
1544 gettimeofday(&tvT, nullptr);
1545 if ((tvStop.tv_sec > tvT.tv_sec)
1546 || ((tvStop.tv_sec == tvT.tv_sec)
1547 && (tvStop.tv_usec > tvT.tv_usec))) {
1548 ptvWait->tv_sec = tvStop.tv_sec - tvT.tv_sec;
1549 ptvWait->tv_usec = tvStop.tv_usec - tvT.tv_usec;
1550 if (ptvWait->tv_usec < 0) {
1551 RTC_DCHECK(ptvWait->tv_sec > 0);
1552 ptvWait->tv_usec += 1000000;
1553 ptvWait->tv_sec -= 1;
1554 }
1555 }
1556 }
1557 }
1558
1559 return true;
1560 }
1561
1562 #if defined(WEBRTC_USE_EPOLL)
1563
1564 // Initial number of events to process with one call to "epoll_wait".
1565 static const size_t kInitialEpollEvents = 128;
1566
1567 // Maximum number of events to process with one call to "epoll_wait".
1568 static const size_t kMaxEpollEvents = 8192;
1569
AddEpoll(Dispatcher * pdispatcher)1570 void PhysicalSocketServer::AddEpoll(Dispatcher* pdispatcher) {
1571 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1572 int fd = pdispatcher->GetDescriptor();
1573 RTC_DCHECK(fd != INVALID_SOCKET);
1574 if (fd == INVALID_SOCKET) {
1575 return;
1576 }
1577
1578 struct epoll_event event = {0};
1579 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
1580 event.data.ptr = pdispatcher;
1581 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &event);
1582 RTC_DCHECK_EQ(err, 0);
1583 if (err == -1) {
1584 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_ADD";
1585 }
1586 }
1587
RemoveEpoll(Dispatcher * pdispatcher)1588 void PhysicalSocketServer::RemoveEpoll(Dispatcher* pdispatcher) {
1589 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1590 int fd = pdispatcher->GetDescriptor();
1591 RTC_DCHECK(fd != INVALID_SOCKET);
1592 if (fd == INVALID_SOCKET) {
1593 return;
1594 }
1595
1596 struct epoll_event event = {0};
1597 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &event);
1598 RTC_DCHECK(err == 0 || errno == ENOENT);
1599 if (err == -1) {
1600 if (errno == ENOENT) {
1601 // Socket has already been closed.
1602 RTC_LOG_E(LS_VERBOSE, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
1603 } else {
1604 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
1605 }
1606 }
1607 }
1608
UpdateEpoll(Dispatcher * pdispatcher)1609 void PhysicalSocketServer::UpdateEpoll(Dispatcher* pdispatcher) {
1610 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1611 int fd = pdispatcher->GetDescriptor();
1612 RTC_DCHECK(fd != INVALID_SOCKET);
1613 if (fd == INVALID_SOCKET) {
1614 return;
1615 }
1616
1617 struct epoll_event event = {0};
1618 event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
1619 event.data.ptr = pdispatcher;
1620 int err = epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &event);
1621 RTC_DCHECK_EQ(err, 0);
1622 if (err == -1) {
1623 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_MOD";
1624 }
1625 }
1626
WaitEpoll(int cmsWait)1627 bool PhysicalSocketServer::WaitEpoll(int cmsWait) {
1628 RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
1629 int64_t tvWait = -1;
1630 int64_t tvStop = -1;
1631 if (cmsWait != kForever) {
1632 tvWait = cmsWait;
1633 tvStop = TimeAfter(cmsWait);
1634 }
1635
1636 if (epoll_events_.empty()) {
1637 // The initial space to receive events is created only if epoll is used.
1638 epoll_events_.resize(kInitialEpollEvents);
1639 }
1640
1641 fWait_ = true;
1642
1643 while (fWait_) {
1644 // Wait then call handlers as appropriate
1645 // < 0 means error
1646 // 0 means timeout
1647 // > 0 means count of descriptors ready
1648 int n = epoll_wait(epoll_fd_, &epoll_events_[0],
1649 static_cast<int>(epoll_events_.size()),
1650 static_cast<int>(tvWait));
1651 if (n < 0) {
1652 if (errno != EINTR) {
1653 RTC_LOG_E(LS_ERROR, EN, errno) << "epoll";
1654 return false;
1655 }
1656 // Else ignore the error and keep going. If this EINTR was for one of the
1657 // signals managed by this PhysicalSocketServer, the
1658 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1659 // iteration.
1660 } else if (n == 0) {
1661 // If timeout, return success
1662 return true;
1663 } else {
1664 // We have signaled descriptors
1665 CritScope cr(&crit_);
1666 for (int i = 0; i < n; ++i) {
1667 const epoll_event& event = epoll_events_[i];
1668 Dispatcher* pdispatcher = static_cast<Dispatcher*>(event.data.ptr);
1669 if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
1670 // The dispatcher for this socket no longer exists.
1671 continue;
1672 }
1673
1674 bool readable = (event.events & (EPOLLIN | EPOLLPRI));
1675 bool writable = (event.events & EPOLLOUT);
1676 bool check_error = (event.events & (EPOLLRDHUP | EPOLLERR | EPOLLHUP));
1677
1678 ProcessEvents(pdispatcher, readable, writable, check_error);
1679 }
1680 }
1681
1682 if (static_cast<size_t>(n) == epoll_events_.size() &&
1683 epoll_events_.size() < kMaxEpollEvents) {
1684 // We used the complete space to receive events, increase size for future
1685 // iterations.
1686 epoll_events_.resize(std::max(epoll_events_.size() * 2, kMaxEpollEvents));
1687 }
1688
1689 if (cmsWait != kForever) {
1690 tvWait = TimeDiff(tvStop, TimeMillis());
1691 if (tvWait < 0) {
1692 // Return success on timeout.
1693 return true;
1694 }
1695 }
1696 }
1697
1698 return true;
1699 }
1700
WaitPoll(int cmsWait,Dispatcher * dispatcher)1701 bool PhysicalSocketServer::WaitPoll(int cmsWait, Dispatcher* dispatcher) {
1702 RTC_DCHECK(dispatcher);
1703 int64_t tvWait = -1;
1704 int64_t tvStop = -1;
1705 if (cmsWait != kForever) {
1706 tvWait = cmsWait;
1707 tvStop = TimeAfter(cmsWait);
1708 }
1709
1710 fWait_ = true;
1711
1712 struct pollfd fds = {0};
1713 int fd = dispatcher->GetDescriptor();
1714 fds.fd = fd;
1715
1716 while (fWait_) {
1717 uint32_t ff = dispatcher->GetRequestedEvents();
1718 fds.events = 0;
1719 if (ff & (DE_READ | DE_ACCEPT)) {
1720 fds.events |= POLLIN;
1721 }
1722 if (ff & (DE_WRITE | DE_CONNECT)) {
1723 fds.events |= POLLOUT;
1724 }
1725 fds.revents = 0;
1726
1727 // Wait then call handlers as appropriate
1728 // < 0 means error
1729 // 0 means timeout
1730 // > 0 means count of descriptors ready
1731 int n = poll(&fds, 1, static_cast<int>(tvWait));
1732 if (n < 0) {
1733 if (errno != EINTR) {
1734 RTC_LOG_E(LS_ERROR, EN, errno) << "poll";
1735 return false;
1736 }
1737 // Else ignore the error and keep going. If this EINTR was for one of the
1738 // signals managed by this PhysicalSocketServer, the
1739 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1740 // iteration.
1741 } else if (n == 0) {
1742 // If timeout, return success
1743 return true;
1744 } else {
1745 // We have signaled descriptors (should only be the passed dispatcher).
1746 RTC_DCHECK_EQ(n, 1);
1747 RTC_DCHECK_EQ(fds.fd, fd);
1748
1749 bool readable = (fds.revents & (POLLIN | POLLPRI));
1750 bool writable = (fds.revents & POLLOUT);
1751 bool check_error = (fds.revents & (POLLRDHUP | POLLERR | POLLHUP));
1752
1753 ProcessEvents(dispatcher, readable, writable, check_error);
1754 }
1755
1756 if (cmsWait != kForever) {
1757 tvWait = TimeDiff(tvStop, TimeMillis());
1758 if (tvWait < 0) {
1759 // Return success on timeout.
1760 return true;
1761 }
1762 }
1763 }
1764
1765 return true;
1766 }
1767
1768 #endif // WEBRTC_USE_EPOLL
1769
GlobalSignalHandler(int signum)1770 static void GlobalSignalHandler(int signum) {
1771 PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
1772 }
1773
SetPosixSignalHandler(int signum,void (* handler)(int))1774 bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
1775 void (*handler)(int)) {
1776 // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
1777 // otherwise set one.
1778 if (handler == SIG_IGN || handler == SIG_DFL) {
1779 if (!InstallSignal(signum, handler)) {
1780 return false;
1781 }
1782 if (signal_dispatcher_) {
1783 signal_dispatcher_->ClearHandler(signum);
1784 if (!signal_dispatcher_->HasHandlers()) {
1785 signal_dispatcher_.reset();
1786 }
1787 }
1788 } else {
1789 if (!signal_dispatcher_) {
1790 signal_dispatcher_.reset(new PosixSignalDispatcher(this));
1791 }
1792 signal_dispatcher_->SetHandler(signum, handler);
1793 if (!InstallSignal(signum, &GlobalSignalHandler)) {
1794 return false;
1795 }
1796 }
1797 return true;
1798 }
1799
signal_dispatcher()1800 Dispatcher* PhysicalSocketServer::signal_dispatcher() {
1801 return signal_dispatcher_.get();
1802 }
1803
InstallSignal(int signum,void (* handler)(int))1804 bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
1805 struct sigaction act;
1806 // It doesn't really matter what we set this mask to.
1807 if (sigemptyset(&act.sa_mask) != 0) {
1808 RTC_LOG_ERR(LS_ERROR) << "Couldn't set mask";
1809 return false;
1810 }
1811 act.sa_handler = handler;
1812 #if !defined(__native_client__)
1813 // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
1814 // and it's a nuisance. Though some syscalls still return EINTR and there's no
1815 // real standard for which ones. :(
1816 act.sa_flags = SA_RESTART;
1817 #else
1818 act.sa_flags = 0;
1819 #endif
1820 if (sigaction(signum, &act, nullptr) != 0) {
1821 RTC_LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
1822 return false;
1823 }
1824 return true;
1825 }
1826 #endif // WEBRTC_POSIX
1827
1828 #if defined(WEBRTC_WIN)
Wait(int cmsWait,bool process_io)1829 bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
1830 int64_t cmsTotal = cmsWait;
1831 int64_t cmsElapsed = 0;
1832 int64_t msStart = Time();
1833
1834 fWait_ = true;
1835 while (fWait_) {
1836 std::vector<WSAEVENT> events;
1837 std::vector<Dispatcher *> event_owners;
1838
1839 events.push_back(socket_ev_);
1840
1841 {
1842 CritScope cr(&crit_);
1843 // TODO(jbauch): Support re-entrant waiting.
1844 RTC_DCHECK(!processing_dispatchers_);
1845
1846 // Calling "CheckSignalClose" might remove a closed dispatcher from the
1847 // set. This must be deferred to prevent invalidating the iterator.
1848 processing_dispatchers_ = true;
1849 for (Dispatcher* disp : dispatchers_) {
1850 if (!process_io && (disp != signal_wakeup_))
1851 continue;
1852 SOCKET s = disp->GetSocket();
1853 if (disp->CheckSignalClose()) {
1854 // We just signalled close, don't poll this socket
1855 } else if (s != INVALID_SOCKET) {
1856 WSAEventSelect(s,
1857 events[0],
1858 FlagsToEvents(disp->GetRequestedEvents()));
1859 } else {
1860 events.push_back(disp->GetWSAEvent());
1861 event_owners.push_back(disp);
1862 }
1863 }
1864
1865 processing_dispatchers_ = false;
1866 // Process deferred dispatchers that have been added/removed while the
1867 // events were handled above.
1868 AddRemovePendingDispatchers();
1869 }
1870
1871 // Which is shorter, the delay wait or the asked wait?
1872
1873 int64_t cmsNext;
1874 if (cmsWait == kForever) {
1875 cmsNext = cmsWait;
1876 } else {
1877 cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
1878 }
1879
1880 // Wait for one of the events to signal
1881 DWORD dw = WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()),
1882 &events[0],
1883 false,
1884 static_cast<DWORD>(cmsNext),
1885 false);
1886
1887 if (dw == WSA_WAIT_FAILED) {
1888 // Failed?
1889 // TODO(pthatcher): need a better strategy than this!
1890 WSAGetLastError();
1891 RTC_NOTREACHED();
1892 return false;
1893 } else if (dw == WSA_WAIT_TIMEOUT) {
1894 // Timeout?
1895 return true;
1896 } else {
1897 // Figure out which one it is and call it
1898 CritScope cr(&crit_);
1899 int index = dw - WSA_WAIT_EVENT_0;
1900 if (index > 0) {
1901 --index; // The first event is the socket event
1902 Dispatcher* disp = event_owners[index];
1903 // The dispatcher could have been removed while waiting for events.
1904 if (dispatchers_.find(disp) != dispatchers_.end()) {
1905 disp->OnPreEvent(0);
1906 disp->OnEvent(0, 0);
1907 }
1908 } else if (process_io) {
1909 processing_dispatchers_ = true;
1910 for (Dispatcher* disp : dispatchers_) {
1911 SOCKET s = disp->GetSocket();
1912 if (s == INVALID_SOCKET)
1913 continue;
1914
1915 WSANETWORKEVENTS wsaEvents;
1916 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1917 if (err == 0) {
1918 {
1919 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1920 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
1921 RTC_LOG(WARNING)
1922 << "PhysicalSocketServer got FD_READ_BIT error "
1923 << wsaEvents.iErrorCode[FD_READ_BIT];
1924 }
1925 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1926 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
1927 RTC_LOG(WARNING)
1928 << "PhysicalSocketServer got FD_WRITE_BIT error "
1929 << wsaEvents.iErrorCode[FD_WRITE_BIT];
1930 }
1931 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1932 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
1933 RTC_LOG(WARNING)
1934 << "PhysicalSocketServer got FD_CONNECT_BIT error "
1935 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
1936 }
1937 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1938 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
1939 RTC_LOG(WARNING)
1940 << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1941 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
1942 }
1943 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1944 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
1945 RTC_LOG(WARNING)
1946 << "PhysicalSocketServer got FD_CLOSE_BIT error "
1947 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
1948 }
1949 }
1950 uint32_t ff = 0;
1951 int errcode = 0;
1952 if (wsaEvents.lNetworkEvents & FD_READ)
1953 ff |= DE_READ;
1954 if (wsaEvents.lNetworkEvents & FD_WRITE)
1955 ff |= DE_WRITE;
1956 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1957 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1958 ff |= DE_CONNECT;
1959 } else {
1960 ff |= DE_CLOSE;
1961 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1962 }
1963 }
1964 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1965 ff |= DE_ACCEPT;
1966 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1967 ff |= DE_CLOSE;
1968 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1969 }
1970 if (ff != 0) {
1971 disp->OnPreEvent(ff);
1972 disp->OnEvent(ff, errcode);
1973 }
1974 }
1975 }
1976
1977 processing_dispatchers_ = false;
1978 // Process deferred dispatchers that have been added/removed while the
1979 // events were handled above.
1980 AddRemovePendingDispatchers();
1981 }
1982
1983 // Reset the network event until new activity occurs
1984 WSAResetEvent(socket_ev_);
1985 }
1986
1987 // Break?
1988 if (!fWait_)
1989 break;
1990 cmsElapsed = TimeSince(msStart);
1991 if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
1992 break;
1993 }
1994 }
1995
1996 // Done
1997 return true;
1998 }
1999 #endif // WEBRTC_WIN
2000
2001 } // namespace rtc
2002