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