blob: 28b410306c1cfd9d3233cae280f77b155e44e9fd [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#if defined(_MSC_VER) && _MSC_VER < 1300
12#pragma warning(disable:4786)
13#endif
14
15#include <assert.h>
16
pbos@webrtc.org27e58982014-10-07 17:56:53 +000017#ifdef MEMORY_SANITIZER
18#include <sanitizer/msan_interface.h>
19#endif
20
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000021#if defined(WEBRTC_POSIX)
22#include <string.h>
23#include <errno.h>
24#include <fcntl.h>
25#include <sys/time.h>
26#include <sys/select.h>
27#include <unistd.h>
28#include <signal.h>
29#endif
30
31#if defined(WEBRTC_WIN)
32#define WIN32_LEAN_AND_MEAN
33#include <windows.h>
34#include <winsock2.h>
35#include <ws2tcpip.h>
36#undef SetPort
37#endif
38
39#include <algorithm>
40#include <map>
41
42#include "webrtc/base/basictypes.h"
43#include "webrtc/base/byteorder.h"
44#include "webrtc/base/common.h"
45#include "webrtc/base/logging.h"
46#include "webrtc/base/nethelpers.h"
47#include "webrtc/base/physicalsocketserver.h"
48#include "webrtc/base/timeutils.h"
49#include "webrtc/base/winping.h"
50#include "webrtc/base/win32socketinit.h"
51
52// stm: this will tell us if we are on OSX
53#ifdef HAVE_CONFIG_H
54#include "config.h"
55#endif
56
57#if defined(WEBRTC_POSIX)
58#include <netinet/tcp.h> // for TCP_NODELAY
59#define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h
60typedef void* SockOptArg;
61#endif // WEBRTC_POSIX
62
63#if defined(WEBRTC_WIN)
64typedef char* SockOptArg;
65#endif
66
67namespace rtc {
68
69#if defined(WEBRTC_WIN)
70// Standard MTUs, from RFC 1191
71const uint16 PACKET_MAXIMUMS[] = {
72 65535, // Theoretical maximum, Hyperchannel
73 32000, // Nothing
74 17914, // 16Mb IBM Token Ring
75 8166, // IEEE 802.4
76 //4464, // IEEE 802.5 (4Mb max)
77 4352, // FDDI
78 //2048, // Wideband Network
79 2002, // IEEE 802.5 (4Mb recommended)
80 //1536, // Expermental Ethernet Networks
81 //1500, // Ethernet, Point-to-Point (default)
82 1492, // IEEE 802.3
83 1006, // SLIP, ARPANET
84 //576, // X.25 Networks
85 //544, // DEC IP Portal
86 //512, // NETBIOS
87 508, // IEEE 802/Source-Rt Bridge, ARCNET
88 296, // Point-to-Point (low delay)
89 68, // Official minimum
90 0, // End of list marker
91};
92
93static const int IP_HEADER_SIZE = 20u;
94static const int IPV6_HEADER_SIZE = 40u;
95static const int ICMP_HEADER_SIZE = 8u;
96static const int ICMP_PING_TIMEOUT_MILLIS = 10000u;
97#endif
98
99class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
100 public:
101 PhysicalSocket(PhysicalSocketServer* ss, SOCKET s = INVALID_SOCKET)
102 : ss_(ss), s_(s), enabled_events_(0), error_(0),
103 state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED),
104 resolver_(NULL) {
105#if defined(WEBRTC_WIN)
106 // EnsureWinsockInit() ensures that winsock is initialized. The default
107 // version of this function doesn't do anything because winsock is
108 // initialized by constructor of a static object. If neccessary libjingle
109 // users can link it with a different version of this function by replacing
110 // win32socketinit.cc. See win32socketinit.cc for more details.
111 EnsureWinsockInit();
112#endif
113 if (s_ != INVALID_SOCKET) {
114 enabled_events_ = DE_READ | DE_WRITE;
115
116 int type = SOCK_STREAM;
117 socklen_t len = sizeof(type);
118 VERIFY(0 == getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len));
119 udp_ = (SOCK_DGRAM == type);
120 }
121 }
122
123 virtual ~PhysicalSocket() {
124 Close();
125 }
126
127 // Creates the underlying OS socket (same as the "socket" function).
128 virtual bool Create(int family, int type) {
129 Close();
130 s_ = ::socket(family, type, 0);
131 udp_ = (SOCK_DGRAM == type);
132 UpdateLastError();
133 if (udp_)
134 enabled_events_ = DE_READ | DE_WRITE;
135 return s_ != INVALID_SOCKET;
136 }
137
138 SocketAddress GetLocalAddress() const {
139 sockaddr_storage addr_storage = {0};
140 socklen_t addrlen = sizeof(addr_storage);
141 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
142 int result = ::getsockname(s_, addr, &addrlen);
143 SocketAddress address;
144 if (result >= 0) {
145 SocketAddressFromSockAddrStorage(addr_storage, &address);
146 } else {
147 LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
148 << s_;
149 }
150 return address;
151 }
152
153 SocketAddress GetRemoteAddress() const {
154 sockaddr_storage addr_storage = {0};
155 socklen_t addrlen = sizeof(addr_storage);
156 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
157 int result = ::getpeername(s_, addr, &addrlen);
158 SocketAddress address;
159 if (result >= 0) {
160 SocketAddressFromSockAddrStorage(addr_storage, &address);
161 } else {
162 LOG(LS_WARNING) << "GetRemoteAddress: unable to get remote addr, socket="
163 << s_;
164 }
165 return address;
166 }
167
168 int Bind(const SocketAddress& bind_addr) {
169 sockaddr_storage addr_storage;
170 size_t len = bind_addr.ToSockAddrStorage(&addr_storage);
171 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
172 int err = ::bind(s_, addr, static_cast<int>(len));
173 UpdateLastError();
174#ifdef _DEBUG
175 if (0 == err) {
176 dbg_addr_ = "Bound @ ";
177 dbg_addr_.append(GetLocalAddress().ToString());
178 }
179#endif // _DEBUG
180 return err;
181 }
182
183 int Connect(const SocketAddress& addr) {
184 // TODO: Implicit creation is required to reconnect...
185 // ...but should we make it more explicit?
186 if (state_ != CS_CLOSED) {
187 SetError(EALREADY);
188 return SOCKET_ERROR;
189 }
190 if (addr.IsUnresolved()) {
191 LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
192 resolver_ = new AsyncResolver();
193 resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult);
194 resolver_->Start(addr);
195 state_ = CS_CONNECTING;
196 return 0;
197 }
198
199 return DoConnect(addr);
200 }
201
202 int DoConnect(const SocketAddress& connect_addr) {
203 if ((s_ == INVALID_SOCKET) &&
204 !Create(connect_addr.family(), SOCK_STREAM)) {
205 return SOCKET_ERROR;
206 }
207 sockaddr_storage addr_storage;
208 size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
209 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
210 int err = ::connect(s_, addr, static_cast<int>(len));
211 UpdateLastError();
212 if (err == 0) {
213 state_ = CS_CONNECTED;
214 } else if (IsBlockingError(GetError())) {
215 state_ = CS_CONNECTING;
216 enabled_events_ |= DE_CONNECT;
217 } else {
218 return SOCKET_ERROR;
219 }
220
221 enabled_events_ |= DE_READ | DE_WRITE;
222 return 0;
223 }
224
225 int GetError() const {
226 CritScope cs(&crit_);
227 return error_;
228 }
229
230 void SetError(int error) {
231 CritScope cs(&crit_);
232 error_ = error;
233 }
234
235 ConnState GetState() const {
236 return state_;
237 }
238
239 int GetOption(Option opt, int* value) {
240 int slevel;
241 int sopt;
242 if (TranslateOption(opt, &slevel, &sopt) == -1)
243 return -1;
244 socklen_t optlen = sizeof(*value);
245 int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
246 if (ret != -1 && opt == OPT_DONTFRAGMENT) {
247#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
248 *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
249#endif
250 }
251 return ret;
252 }
253
254 int SetOption(Option opt, int value) {
255 int slevel;
256 int sopt;
257 if (TranslateOption(opt, &slevel, &sopt) == -1)
258 return -1;
259 if (opt == OPT_DONTFRAGMENT) {
260#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
261 value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
262#endif
263 }
264 return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
265 }
266
267 int Send(const void *pv, size_t cb) {
268 int sent = ::send(s_, reinterpret_cast<const char *>(pv), (int)cb,
269#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
270 // Suppress SIGPIPE. Without this, attempting to send on a socket whose
271 // other end is closed will result in a SIGPIPE signal being raised to
272 // our process, which by default will terminate the process, which we
273 // don't want. By specifying this flag, we'll just get the error EPIPE
274 // instead and can handle the error gracefully.
275 MSG_NOSIGNAL
276#else
277 0
278#endif
279 );
280 UpdateLastError();
281 MaybeRemapSendError();
282 // We have seen minidumps where this may be false.
283 ASSERT(sent <= static_cast<int>(cb));
284 if ((sent < 0) && IsBlockingError(GetError())) {
285 enabled_events_ |= DE_WRITE;
286 }
287 return sent;
288 }
289
290 int SendTo(const void* buffer, size_t length, const SocketAddress& addr) {
291 sockaddr_storage saddr;
292 size_t len = addr.ToSockAddrStorage(&saddr);
293 int sent = ::sendto(
294 s_, static_cast<const char *>(buffer), static_cast<int>(length),
295#if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
296 // Suppress SIGPIPE. See above for explanation.
297 MSG_NOSIGNAL,
298#else
299 0,
300#endif
301 reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
302 UpdateLastError();
303 MaybeRemapSendError();
304 // We have seen minidumps where this may be false.
305 ASSERT(sent <= static_cast<int>(length));
306 if ((sent < 0) && IsBlockingError(GetError())) {
307 enabled_events_ |= DE_WRITE;
308 }
309 return sent;
310 }
311
312 int Recv(void* buffer, size_t length) {
313 int received = ::recv(s_, static_cast<char*>(buffer),
314 static_cast<int>(length), 0);
315 if ((received == 0) && (length != 0)) {
316 // Note: on graceful shutdown, recv can return 0. In this case, we
317 // pretend it is blocking, and then signal close, so that simplifying
318 // assumptions can be made about Recv.
319 LOG(LS_WARNING) << "EOF from socket; deferring close event";
320 // Must turn this back on so that the select() loop will notice the close
321 // event.
322 enabled_events_ |= DE_READ;
323 SetError(EWOULDBLOCK);
324 return SOCKET_ERROR;
325 }
326 UpdateLastError();
327 int error = GetError();
328 bool success = (received >= 0) || IsBlockingError(error);
329 if (udp_ || success) {
330 enabled_events_ |= DE_READ;
331 }
332 if (!success) {
333 LOG_F(LS_VERBOSE) << "Error = " << error;
334 }
335 return received;
336 }
337
338 int RecvFrom(void* buffer, size_t length, SocketAddress *out_addr) {
339 sockaddr_storage addr_storage;
340 socklen_t addr_len = sizeof(addr_storage);
341 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
342 int received = ::recvfrom(s_, static_cast<char*>(buffer),
343 static_cast<int>(length), 0, addr, &addr_len);
344 UpdateLastError();
345 if ((received >= 0) && (out_addr != NULL))
346 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
347 int error = GetError();
348 bool success = (received >= 0) || IsBlockingError(error);
349 if (udp_ || success) {
350 enabled_events_ |= DE_READ;
351 }
352 if (!success) {
353 LOG_F(LS_VERBOSE) << "Error = " << error;
354 }
355 return received;
356 }
357
358 int Listen(int backlog) {
359 int err = ::listen(s_, backlog);
360 UpdateLastError();
361 if (err == 0) {
362 state_ = CS_CONNECTING;
363 enabled_events_ |= DE_ACCEPT;
364#ifdef _DEBUG
365 dbg_addr_ = "Listening @ ";
366 dbg_addr_.append(GetLocalAddress().ToString());
367#endif // _DEBUG
368 }
369 return err;
370 }
371
372 AsyncSocket* Accept(SocketAddress *out_addr) {
373 sockaddr_storage addr_storage;
374 socklen_t addr_len = sizeof(addr_storage);
375 sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
376 SOCKET s = ::accept(s_, addr, &addr_len);
377 UpdateLastError();
378 if (s == INVALID_SOCKET)
379 return NULL;
380 enabled_events_ |= DE_ACCEPT;
381 if (out_addr != NULL)
382 SocketAddressFromSockAddrStorage(addr_storage, out_addr);
383 return ss_->WrapSocket(s);
384 }
385
386 int Close() {
387 if (s_ == INVALID_SOCKET)
388 return 0;
389 int err = ::closesocket(s_);
390 UpdateLastError();
391 s_ = INVALID_SOCKET;
392 state_ = CS_CLOSED;
393 enabled_events_ = 0;
394 if (resolver_) {
395 resolver_->Destroy(false);
396 resolver_ = NULL;
397 }
398 return err;
399 }
400
401 int EstimateMTU(uint16* mtu) {
402 SocketAddress addr = GetRemoteAddress();
403 if (addr.IsAny()) {
404 SetError(ENOTCONN);
405 return -1;
406 }
407
408#if defined(WEBRTC_WIN)
409 // Gets the interface MTU (TTL=1) for the interface used to reach |addr|.
410 WinPing ping;
411 if (!ping.IsValid()) {
412 SetError(EINVAL); // can't think of a better error ID
413 return -1;
414 }
415 int header_size = ICMP_HEADER_SIZE;
416 if (addr.family() == AF_INET6) {
417 header_size += IPV6_HEADER_SIZE;
418 } else if (addr.family() == AF_INET) {
419 header_size += IP_HEADER_SIZE;
420 }
421
422 for (int level = 0; PACKET_MAXIMUMS[level + 1] > 0; ++level) {
423 int32 size = PACKET_MAXIMUMS[level] - header_size;
424 WinPing::PingResult result = ping.Ping(addr.ipaddr(), size,
425 ICMP_PING_TIMEOUT_MILLIS,
426 1, false);
427 if (result == WinPing::PING_FAIL) {
428 SetError(EINVAL); // can't think of a better error ID
429 return -1;
430 } else if (result != WinPing::PING_TOO_LARGE) {
431 *mtu = PACKET_MAXIMUMS[level];
432 return 0;
433 }
434 }
435
436 ASSERT(false);
437 return -1;
438#elif defined(WEBRTC_MAC)
439 // No simple way to do this on Mac OS X.
440 // SIOCGIFMTU would work if we knew which interface would be used, but
441 // figuring that out is pretty complicated. For now we'll return an error
442 // and let the caller pick a default MTU.
443 SetError(EINVAL);
444 return -1;
445#elif defined(WEBRTC_LINUX)
446 // Gets the path MTU.
447 int value;
448 socklen_t vlen = sizeof(value);
449 int err = getsockopt(s_, IPPROTO_IP, IP_MTU, &value, &vlen);
450 if (err < 0) {
451 UpdateLastError();
452 return err;
453 }
454
455 ASSERT((0 <= value) && (value <= 65536));
456 *mtu = value;
457 return 0;
458#elif defined(__native_client__)
459 // Most socket operations, including this, will fail in NaCl's sandbox.
460 error_ = EACCES;
461 return -1;
462#endif
463 }
464
465 SocketServer* socketserver() { return ss_; }
466
467 protected:
468 void OnResolveResult(AsyncResolverInterface* resolver) {
469 if (resolver != resolver_) {
470 return;
471 }
472
473 int error = resolver_->GetError();
474 if (error == 0) {
475 error = DoConnect(resolver_->address());
476 } else {
477 Close();
478 }
479
480 if (error) {
481 SetError(error);
482 SignalCloseEvent(this, error);
483 }
484 }
485
486 void UpdateLastError() {
487 SetError(LAST_SYSTEM_ERROR);
488 }
489
490 void MaybeRemapSendError() {
491#if defined(WEBRTC_MAC)
492 // https://developer.apple.com/library/mac/documentation/Darwin/
493 // Reference/ManPages/man2/sendto.2.html
494 // ENOBUFS - The output queue for a network interface is full.
495 // This generally indicates that the interface has stopped sending,
496 // but may be caused by transient congestion.
497 if (GetError() == ENOBUFS) {
498 SetError(EWOULDBLOCK);
499 }
500#endif
501 }
502
503 static int TranslateOption(Option opt, int* slevel, int* sopt) {
504 switch (opt) {
505 case OPT_DONTFRAGMENT:
506#if defined(WEBRTC_WIN)
507 *slevel = IPPROTO_IP;
508 *sopt = IP_DONTFRAGMENT;
509 break;
510#elif defined(WEBRTC_MAC) || defined(BSD) || defined(__native_client__)
511 LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
512 return -1;
513#elif defined(WEBRTC_POSIX)
514 *slevel = IPPROTO_IP;
515 *sopt = IP_MTU_DISCOVER;
516 break;
517#endif
518 case OPT_RCVBUF:
519 *slevel = SOL_SOCKET;
520 *sopt = SO_RCVBUF;
521 break;
522 case OPT_SNDBUF:
523 *slevel = SOL_SOCKET;
524 *sopt = SO_SNDBUF;
525 break;
526 case OPT_NODELAY:
527 *slevel = IPPROTO_TCP;
528 *sopt = TCP_NODELAY;
529 break;
530 case OPT_DSCP:
531 LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
532 return -1;
533 case OPT_RTP_SENDTIME_EXTN_ID:
534 return -1; // No logging is necessary as this not a OS socket option.
535 default:
536 ASSERT(false);
537 return -1;
538 }
539 return 0;
540 }
541
542 PhysicalSocketServer* ss_;
543 SOCKET s_;
544 uint8 enabled_events_;
545 bool udp_;
546 int error_;
547 // Protects |error_| that is accessed from different threads.
548 mutable CriticalSection crit_;
549 ConnState state_;
550 AsyncResolver* resolver_;
551
552#ifdef _DEBUG
553 std::string dbg_addr_;
554#endif // _DEBUG;
555};
556
557#if defined(WEBRTC_POSIX)
558class EventDispatcher : public Dispatcher {
559 public:
560 EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
561 if (pipe(afd_) < 0)
562 LOG(LERROR) << "pipe failed";
563 ss_->Add(this);
564 }
565
566 virtual ~EventDispatcher() {
567 ss_->Remove(this);
568 close(afd_[0]);
569 close(afd_[1]);
570 }
571
572 virtual void Signal() {
573 CritScope cs(&crit_);
574 if (!fSignaled_) {
575 const uint8 b[1] = { 0 };
576 if (VERIFY(1 == write(afd_[1], b, sizeof(b)))) {
577 fSignaled_ = true;
578 }
579 }
580 }
581
582 virtual uint32 GetRequestedEvents() {
583 return DE_READ;
584 }
585
586 virtual void OnPreEvent(uint32 ff) {
587 // It is not possible to perfectly emulate an auto-resetting event with
588 // pipes. This simulates it by resetting before the event is handled.
589
590 CritScope cs(&crit_);
591 if (fSignaled_) {
592 uint8 b[4]; // Allow for reading more than 1 byte, but expect 1.
593 VERIFY(1 == read(afd_[0], b, sizeof(b)));
594 fSignaled_ = false;
595 }
596 }
597
598 virtual void OnEvent(uint32 ff, int err) {
599 ASSERT(false);
600 }
601
602 virtual int GetDescriptor() {
603 return afd_[0];
604 }
605
606 virtual bool IsDescriptorClosed() {
607 return false;
608 }
609
610 private:
611 PhysicalSocketServer *ss_;
612 int afd_[2];
613 bool fSignaled_;
614 CriticalSection crit_;
615};
616
617// These two classes use the self-pipe trick to deliver POSIX signals to our
618// select loop. This is the only safe, reliable, cross-platform way to do
619// non-trivial things with a POSIX signal in an event-driven program (until
620// proper pselect() implementations become ubiquitous).
621
622class PosixSignalHandler {
623 public:
624 // POSIX only specifies 32 signals, but in principle the system might have
625 // more and the programmer might choose to use them, so we size our array
626 // for 128.
627 static const int kNumPosixSignals = 128;
628
629 // There is just a single global instance. (Signal handlers do not get any
630 // sort of user-defined void * parameter, so they can't access anything that
631 // isn't global.)
632 static PosixSignalHandler* Instance() {
633 LIBJINGLE_DEFINE_STATIC_LOCAL(PosixSignalHandler, instance, ());
634 return &instance;
635 }
636
637 // Returns true if the given signal number is set.
638 bool IsSignalSet(int signum) const {
639 ASSERT(signum < ARRAY_SIZE(received_signal_));
640 if (signum < ARRAY_SIZE(received_signal_)) {
641 return received_signal_[signum];
642 } else {
643 return false;
644 }
645 }
646
647 // Clears the given signal number.
648 void ClearSignal(int signum) {
649 ASSERT(signum < ARRAY_SIZE(received_signal_));
650 if (signum < ARRAY_SIZE(received_signal_)) {
651 received_signal_[signum] = false;
652 }
653 }
654
655 // Returns the file descriptor to monitor for signal events.
656 int GetDescriptor() const {
657 return afd_[0];
658 }
659
660 // This is called directly from our real signal handler, so it must be
661 // signal-handler-safe. That means it cannot assume anything about the
662 // user-level state of the process, since the handler could be executed at any
663 // time on any thread.
664 void OnPosixSignalReceived(int signum) {
665 if (signum >= ARRAY_SIZE(received_signal_)) {
666 // We don't have space in our array for this.
667 return;
668 }
669 // Set a flag saying we've seen this signal.
670 received_signal_[signum] = true;
671 // Notify application code that we got a signal.
672 const uint8 b[1] = { 0 };
673 if (-1 == write(afd_[1], b, sizeof(b))) {
674 // Nothing we can do here. If there's an error somehow then there's
675 // nothing we can safely do from a signal handler.
676 // No, we can't even safely log it.
677 // But, we still have to check the return value here. Otherwise,
678 // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
679 return;
680 }
681 }
682
683 private:
684 PosixSignalHandler() {
685 if (pipe(afd_) < 0) {
686 LOG_ERR(LS_ERROR) << "pipe failed";
687 return;
688 }
689 if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
690 LOG_ERR(LS_WARNING) << "fcntl #1 failed";
691 }
692 if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
693 LOG_ERR(LS_WARNING) << "fcntl #2 failed";
694 }
695 memset(const_cast<void *>(static_cast<volatile void *>(received_signal_)),
696 0,
697 sizeof(received_signal_));
698 }
699
700 ~PosixSignalHandler() {
701 int fd1 = afd_[0];
702 int fd2 = afd_[1];
703 // We clobber the stored file descriptor numbers here or else in principle
704 // a signal that happens to be delivered during application termination
705 // could erroneously write a zero byte to an unrelated file handle in
706 // OnPosixSignalReceived() if some other file happens to be opened later
707 // during shutdown and happens to be given the same file descriptor number
708 // as our pipe had. Unfortunately even with this precaution there is still a
709 // race where that could occur if said signal happens to be handled
710 // concurrently with this code and happens to have already read the value of
711 // afd_[1] from memory before we clobber it, but that's unlikely.
712 afd_[0] = -1;
713 afd_[1] = -1;
714 close(fd1);
715 close(fd2);
716 }
717
718 int afd_[2];
719 // These are boolean flags that will be set in our signal handler and read
720 // and cleared from Wait(). There is a race involved in this, but it is
721 // benign. The signal handler sets the flag before signaling the pipe, so
722 // we'll never end up blocking in select() while a flag is still true.
723 // However, if two of the same signal arrive close to each other then it's
724 // possible that the second time the handler may set the flag while it's still
725 // true, meaning that signal will be missed. But the first occurrence of it
726 // will still be handled, so this isn't a problem.
727 // Volatile is not necessary here for correctness, but this data _is_ volatile
728 // so I've marked it as such.
729 volatile uint8 received_signal_[kNumPosixSignals];
730};
731
732class PosixSignalDispatcher : public Dispatcher {
733 public:
734 PosixSignalDispatcher(PhysicalSocketServer *owner) : owner_(owner) {
735 owner_->Add(this);
736 }
737
738 virtual ~PosixSignalDispatcher() {
739 owner_->Remove(this);
740 }
741
742 virtual uint32 GetRequestedEvents() {
743 return DE_READ;
744 }
745
746 virtual void OnPreEvent(uint32 ff) {
747 // Events might get grouped if signals come very fast, so we read out up to
748 // 16 bytes to make sure we keep the pipe empty.
749 uint8 b[16];
750 ssize_t ret = read(GetDescriptor(), b, sizeof(b));
751 if (ret < 0) {
752 LOG_ERR(LS_WARNING) << "Error in read()";
753 } else if (ret == 0) {
754 LOG(LS_WARNING) << "Should have read at least one byte";
755 }
756 }
757
758 virtual void OnEvent(uint32 ff, int err) {
759 for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
760 ++signum) {
761 if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
762 PosixSignalHandler::Instance()->ClearSignal(signum);
763 HandlerMap::iterator i = handlers_.find(signum);
764 if (i == handlers_.end()) {
765 // This can happen if a signal is delivered to our process at around
766 // the same time as we unset our handler for it. It is not an error
767 // condition, but it's unusual enough to be worth logging.
768 LOG(LS_INFO) << "Received signal with no handler: " << signum;
769 } else {
770 // Otherwise, execute our handler.
771 (*i->second)(signum);
772 }
773 }
774 }
775 }
776
777 virtual int GetDescriptor() {
778 return PosixSignalHandler::Instance()->GetDescriptor();
779 }
780
781 virtual bool IsDescriptorClosed() {
782 return false;
783 }
784
785 void SetHandler(int signum, void (*handler)(int)) {
786 handlers_[signum] = handler;
787 }
788
789 void ClearHandler(int signum) {
790 handlers_.erase(signum);
791 }
792
793 bool HasHandlers() {
794 return !handlers_.empty();
795 }
796
797 private:
798 typedef std::map<int, void (*)(int)> HandlerMap;
799
800 HandlerMap handlers_;
801 // Our owner.
802 PhysicalSocketServer *owner_;
803};
804
805class SocketDispatcher : public Dispatcher, public PhysicalSocket {
806 public:
807 explicit SocketDispatcher(PhysicalSocketServer *ss) : PhysicalSocket(ss) {
808 }
809 SocketDispatcher(SOCKET s, PhysicalSocketServer *ss) : PhysicalSocket(ss, s) {
810 }
811
812 virtual ~SocketDispatcher() {
813 Close();
814 }
815
816 bool Initialize() {
817 ss_->Add(this);
818 fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
819 return true;
820 }
821
822 virtual bool Create(int type) {
823 return Create(AF_INET, type);
824 }
825
826 virtual bool Create(int family, int type) {
827 // Change the socket to be non-blocking.
828 if (!PhysicalSocket::Create(family, type))
829 return false;
830
831 return Initialize();
832 }
833
834 virtual int GetDescriptor() {
835 return s_;
836 }
837
838 virtual bool IsDescriptorClosed() {
839 // We don't have a reliable way of distinguishing end-of-stream
840 // from readability. So test on each readable call. Is this
841 // inefficient? Probably.
842 char ch;
843 ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
844 if (res > 0) {
845 // Data available, so not closed.
846 return false;
847 } else if (res == 0) {
848 // EOF, so closed.
849 return true;
850 } else { // error
851 switch (errno) {
852 // Returned if we've already closed s_.
853 case EBADF:
854 // Returned during ungraceful peer shutdown.
855 case ECONNRESET:
856 return true;
857 default:
858 // Assume that all other errors are just blocking errors, meaning the
859 // connection is still good but we just can't read from it right now.
860 // This should only happen when connecting (and at most once), because
861 // in all other cases this function is only called if the file
862 // descriptor is already known to be in the readable state. However,
863 // it's not necessary a problem if we spuriously interpret a
864 // "connection lost"-type error as a blocking error, because typically
865 // the next recv() will get EOF, so we'll still eventually notice that
866 // the socket is closed.
867 LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
868 return false;
869 }
870 }
871 }
872
873 virtual uint32 GetRequestedEvents() {
874 return enabled_events_;
875 }
876
877 virtual void OnPreEvent(uint32 ff) {
878 if ((ff & DE_CONNECT) != 0)
879 state_ = CS_CONNECTED;
880 if ((ff & DE_CLOSE) != 0)
881 state_ = CS_CLOSED;
882 }
883
884 virtual void OnEvent(uint32 ff, int err) {
885 // Make sure we deliver connect/accept first. Otherwise, consumers may see
886 // something like a READ followed by a CONNECT, which would be odd.
887 if ((ff & DE_CONNECT) != 0) {
888 enabled_events_ &= ~DE_CONNECT;
889 SignalConnectEvent(this);
890 }
891 if ((ff & DE_ACCEPT) != 0) {
892 enabled_events_ &= ~DE_ACCEPT;
893 SignalReadEvent(this);
894 }
895 if ((ff & DE_READ) != 0) {
896 enabled_events_ &= ~DE_READ;
897 SignalReadEvent(this);
898 }
899 if ((ff & DE_WRITE) != 0) {
900 enabled_events_ &= ~DE_WRITE;
901 SignalWriteEvent(this);
902 }
903 if ((ff & DE_CLOSE) != 0) {
904 // The socket is now dead to us, so stop checking it.
905 enabled_events_ = 0;
906 SignalCloseEvent(this, err);
907 }
908 }
909
910 virtual int Close() {
911 if (s_ == INVALID_SOCKET)
912 return 0;
913
914 ss_->Remove(this);
915 return PhysicalSocket::Close();
916 }
917};
918
919class FileDispatcher: public Dispatcher, public AsyncFile {
920 public:
921 FileDispatcher(int fd, PhysicalSocketServer *ss) : ss_(ss), fd_(fd) {
922 set_readable(true);
923
924 ss_->Add(this);
925
926 fcntl(fd_, F_SETFL, fcntl(fd_, F_GETFL, 0) | O_NONBLOCK);
927 }
928
929 virtual ~FileDispatcher() {
930 ss_->Remove(this);
931 }
932
933 SocketServer* socketserver() { return ss_; }
934
935 virtual int GetDescriptor() {
936 return fd_;
937 }
938
939 virtual bool IsDescriptorClosed() {
940 return false;
941 }
942
943 virtual uint32 GetRequestedEvents() {
944 return flags_;
945 }
946
947 virtual void OnPreEvent(uint32 ff) {
948 }
949
950 virtual void OnEvent(uint32 ff, int err) {
951 if ((ff & DE_READ) != 0)
952 SignalReadEvent(this);
953 if ((ff & DE_WRITE) != 0)
954 SignalWriteEvent(this);
955 if ((ff & DE_CLOSE) != 0)
956 SignalCloseEvent(this, err);
957 }
958
959 virtual bool readable() {
960 return (flags_ & DE_READ) != 0;
961 }
962
963 virtual void set_readable(bool value) {
964 flags_ = value ? (flags_ | DE_READ) : (flags_ & ~DE_READ);
965 }
966
967 virtual bool writable() {
968 return (flags_ & DE_WRITE) != 0;
969 }
970
971 virtual void set_writable(bool value) {
972 flags_ = value ? (flags_ | DE_WRITE) : (flags_ & ~DE_WRITE);
973 }
974
975 private:
976 PhysicalSocketServer* ss_;
977 int fd_;
978 int flags_;
979};
980
981AsyncFile* PhysicalSocketServer::CreateFile(int fd) {
982 return new FileDispatcher(fd, this);
983}
984
985#endif // WEBRTC_POSIX
986
987#if defined(WEBRTC_WIN)
988static uint32 FlagsToEvents(uint32 events) {
989 uint32 ffFD = FD_CLOSE;
990 if (events & DE_READ)
991 ffFD |= FD_READ;
992 if (events & DE_WRITE)
993 ffFD |= FD_WRITE;
994 if (events & DE_CONNECT)
995 ffFD |= FD_CONNECT;
996 if (events & DE_ACCEPT)
997 ffFD |= FD_ACCEPT;
998 return ffFD;
999}
1000
1001class EventDispatcher : public Dispatcher {
1002 public:
1003 EventDispatcher(PhysicalSocketServer *ss) : ss_(ss) {
1004 hev_ = WSACreateEvent();
1005 if (hev_) {
1006 ss_->Add(this);
1007 }
1008 }
1009
1010 ~EventDispatcher() {
1011 if (hev_ != NULL) {
1012 ss_->Remove(this);
1013 WSACloseEvent(hev_);
1014 hev_ = NULL;
1015 }
1016 }
1017
1018 virtual void Signal() {
1019 if (hev_ != NULL)
1020 WSASetEvent(hev_);
1021 }
1022
1023 virtual uint32 GetRequestedEvents() {
1024 return 0;
1025 }
1026
1027 virtual void OnPreEvent(uint32 ff) {
1028 WSAResetEvent(hev_);
1029 }
1030
1031 virtual void OnEvent(uint32 ff, int err) {
1032 }
1033
1034 virtual WSAEVENT GetWSAEvent() {
1035 return hev_;
1036 }
1037
1038 virtual SOCKET GetSocket() {
1039 return INVALID_SOCKET;
1040 }
1041
1042 virtual bool CheckSignalClose() { return false; }
1043
1044private:
1045 PhysicalSocketServer* ss_;
1046 WSAEVENT hev_;
1047};
1048
1049class SocketDispatcher : public Dispatcher, public PhysicalSocket {
1050 public:
1051 static int next_id_;
1052 int id_;
1053 bool signal_close_;
1054 int signal_err_;
1055
1056 SocketDispatcher(PhysicalSocketServer* ss)
1057 : PhysicalSocket(ss),
1058 id_(0),
1059 signal_close_(false) {
1060 }
1061
1062 SocketDispatcher(SOCKET s, PhysicalSocketServer* ss)
1063 : PhysicalSocket(ss, s),
1064 id_(0),
1065 signal_close_(false) {
1066 }
1067
1068 virtual ~SocketDispatcher() {
1069 Close();
1070 }
1071
1072 bool Initialize() {
1073 ASSERT(s_ != INVALID_SOCKET);
1074 // Must be a non-blocking
1075 u_long argp = 1;
1076 ioctlsocket(s_, FIONBIO, &argp);
1077 ss_->Add(this);
1078 return true;
1079 }
1080
1081 virtual bool Create(int type) {
1082 return Create(AF_INET, type);
1083 }
1084
1085 virtual bool Create(int family, int type) {
1086 // Create socket
1087 if (!PhysicalSocket::Create(family, type))
1088 return false;
1089
1090 if (!Initialize())
1091 return false;
1092
1093 do { id_ = ++next_id_; } while (id_ == 0);
1094 return true;
1095 }
1096
1097 virtual int Close() {
1098 if (s_ == INVALID_SOCKET)
1099 return 0;
1100
1101 id_ = 0;
1102 signal_close_ = false;
1103 ss_->Remove(this);
1104 return PhysicalSocket::Close();
1105 }
1106
1107 virtual uint32 GetRequestedEvents() {
1108 return enabled_events_;
1109 }
1110
1111 virtual void OnPreEvent(uint32 ff) {
1112 if ((ff & DE_CONNECT) != 0)
1113 state_ = CS_CONNECTED;
1114 // We set CS_CLOSED from CheckSignalClose.
1115 }
1116
1117 virtual void OnEvent(uint32 ff, int err) {
1118 int cache_id = id_;
1119 // Make sure we deliver connect/accept first. Otherwise, consumers may see
1120 // something like a READ followed by a CONNECT, which would be odd.
1121 if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
1122 if (ff != DE_CONNECT)
1123 LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
1124 enabled_events_ &= ~DE_CONNECT;
1125#ifdef _DEBUG
1126 dbg_addr_ = "Connected @ ";
1127 dbg_addr_.append(GetRemoteAddress().ToString());
1128#endif // _DEBUG
1129 SignalConnectEvent(this);
1130 }
1131 if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
1132 enabled_events_ &= ~DE_ACCEPT;
1133 SignalReadEvent(this);
1134 }
1135 if ((ff & DE_READ) != 0) {
1136 enabled_events_ &= ~DE_READ;
1137 SignalReadEvent(this);
1138 }
1139 if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
1140 enabled_events_ &= ~DE_WRITE;
1141 SignalWriteEvent(this);
1142 }
1143 if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
1144 signal_close_ = true;
1145 signal_err_ = err;
1146 }
1147 }
1148
1149 virtual WSAEVENT GetWSAEvent() {
1150 return WSA_INVALID_EVENT;
1151 }
1152
1153 virtual SOCKET GetSocket() {
1154 return s_;
1155 }
1156
1157 virtual bool CheckSignalClose() {
1158 if (!signal_close_)
1159 return false;
1160
1161 char ch;
1162 if (recv(s_, &ch, 1, MSG_PEEK) > 0)
1163 return false;
1164
1165 state_ = CS_CLOSED;
1166 signal_close_ = false;
1167 SignalCloseEvent(this, signal_err_);
1168 return true;
1169 }
1170};
1171
1172int SocketDispatcher::next_id_ = 0;
1173
1174#endif // WEBRTC_WIN
1175
1176// Sets the value of a boolean value to false when signaled.
1177class Signaler : public EventDispatcher {
1178 public:
1179 Signaler(PhysicalSocketServer* ss, bool* pf)
1180 : EventDispatcher(ss), pf_(pf) {
1181 }
1182 virtual ~Signaler() { }
1183
1184 void OnEvent(uint32 ff, int err) {
1185 if (pf_)
1186 *pf_ = false;
1187 }
1188
1189 private:
1190 bool *pf_;
1191};
1192
1193PhysicalSocketServer::PhysicalSocketServer()
1194 : fWait_(false) {
1195 signal_wakeup_ = new Signaler(this, &fWait_);
1196#if defined(WEBRTC_WIN)
1197 socket_ev_ = WSACreateEvent();
1198#endif
1199}
1200
1201PhysicalSocketServer::~PhysicalSocketServer() {
1202#if defined(WEBRTC_WIN)
1203 WSACloseEvent(socket_ev_);
1204#endif
1205#if defined(WEBRTC_POSIX)
1206 signal_dispatcher_.reset();
1207#endif
1208 delete signal_wakeup_;
1209 ASSERT(dispatchers_.empty());
1210}
1211
1212void PhysicalSocketServer::WakeUp() {
1213 signal_wakeup_->Signal();
1214}
1215
1216Socket* PhysicalSocketServer::CreateSocket(int type) {
1217 return CreateSocket(AF_INET, type);
1218}
1219
1220Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
1221 PhysicalSocket* socket = new PhysicalSocket(this);
1222 if (socket->Create(family, type)) {
1223 return socket;
1224 } else {
1225 delete socket;
1226 return 0;
1227 }
1228}
1229
1230AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int type) {
1231 return CreateAsyncSocket(AF_INET, type);
1232}
1233
1234AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
1235 SocketDispatcher* dispatcher = new SocketDispatcher(this);
1236 if (dispatcher->Create(family, type)) {
1237 return dispatcher;
1238 } else {
1239 delete dispatcher;
1240 return 0;
1241 }
1242}
1243
1244AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
1245 SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
1246 if (dispatcher->Initialize()) {
1247 return dispatcher;
1248 } else {
1249 delete dispatcher;
1250 return 0;
1251 }
1252}
1253
1254void PhysicalSocketServer::Add(Dispatcher *pdispatcher) {
1255 CritScope cs(&crit_);
1256 // Prevent duplicates. This can cause dead dispatchers to stick around.
1257 DispatcherList::iterator pos = std::find(dispatchers_.begin(),
1258 dispatchers_.end(),
1259 pdispatcher);
1260 if (pos != dispatchers_.end())
1261 return;
1262 dispatchers_.push_back(pdispatcher);
1263}
1264
1265void PhysicalSocketServer::Remove(Dispatcher *pdispatcher) {
1266 CritScope cs(&crit_);
1267 DispatcherList::iterator pos = std::find(dispatchers_.begin(),
1268 dispatchers_.end(),
1269 pdispatcher);
1270 // We silently ignore duplicate calls to Add, so we should silently ignore
1271 // the (expected) symmetric calls to Remove. Note that this may still hide
1272 // a real issue, so we at least log a warning about it.
1273 if (pos == dispatchers_.end()) {
1274 LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
1275 << "dispatcher, potentially from a duplicate call to Add.";
1276 return;
1277 }
1278 size_t index = pos - dispatchers_.begin();
1279 dispatchers_.erase(pos);
1280 for (IteratorList::iterator it = iterators_.begin(); it != iterators_.end();
1281 ++it) {
1282 if (index < **it) {
1283 --**it;
1284 }
1285 }
1286}
1287
1288#if defined(WEBRTC_POSIX)
1289bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
1290 // Calculate timing information
1291
1292 struct timeval *ptvWait = NULL;
1293 struct timeval tvWait;
1294 struct timeval tvStop;
1295 if (cmsWait != kForever) {
1296 // Calculate wait timeval
1297 tvWait.tv_sec = cmsWait / 1000;
1298 tvWait.tv_usec = (cmsWait % 1000) * 1000;
1299 ptvWait = &tvWait;
1300
1301 // Calculate when to return in a timeval
1302 gettimeofday(&tvStop, NULL);
1303 tvStop.tv_sec += tvWait.tv_sec;
1304 tvStop.tv_usec += tvWait.tv_usec;
1305 if (tvStop.tv_usec >= 1000000) {
1306 tvStop.tv_usec -= 1000000;
1307 tvStop.tv_sec += 1;
1308 }
1309 }
1310
1311 // Zero all fd_sets. Don't need to do this inside the loop since
1312 // select() zeros the descriptors not signaled
1313
1314 fd_set fdsRead;
1315 FD_ZERO(&fdsRead);
1316 fd_set fdsWrite;
1317 FD_ZERO(&fdsWrite);
pbos@webrtc.org27e58982014-10-07 17:56:53 +00001318 // Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
1319 // inline assembly in FD_ZERO.
1320 // http://crbug.com/344505
1321#ifdef MEMORY_SANITIZER
1322 __msan_unpoison(&fdsRead, sizeof(fdsRead));
1323 __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
1324#endif
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001325
1326 fWait_ = true;
1327
1328 while (fWait_) {
1329 int fdmax = -1;
1330 {
1331 CritScope cr(&crit_);
1332 for (size_t i = 0; i < dispatchers_.size(); ++i) {
1333 // Query dispatchers for read and write wait state
1334 Dispatcher *pdispatcher = dispatchers_[i];
1335 ASSERT(pdispatcher);
1336 if (!process_io && (pdispatcher != signal_wakeup_))
1337 continue;
1338 int fd = pdispatcher->GetDescriptor();
1339 if (fd > fdmax)
1340 fdmax = fd;
1341
1342 uint32 ff = pdispatcher->GetRequestedEvents();
1343 if (ff & (DE_READ | DE_ACCEPT))
1344 FD_SET(fd, &fdsRead);
1345 if (ff & (DE_WRITE | DE_CONNECT))
1346 FD_SET(fd, &fdsWrite);
1347 }
1348 }
1349
1350 // Wait then call handlers as appropriate
1351 // < 0 means error
1352 // 0 means timeout
1353 // > 0 means count of descriptors ready
1354 int n = select(fdmax + 1, &fdsRead, &fdsWrite, NULL, ptvWait);
1355
1356 // If error, return error.
1357 if (n < 0) {
1358 if (errno != EINTR) {
1359 LOG_E(LS_ERROR, EN, errno) << "select";
1360 return false;
1361 }
1362 // Else ignore the error and keep going. If this EINTR was for one of the
1363 // signals managed by this PhysicalSocketServer, the
1364 // PosixSignalDeliveryDispatcher will be in the signaled state in the next
1365 // iteration.
1366 } else if (n == 0) {
1367 // If timeout, return success
1368 return true;
1369 } else {
1370 // We have signaled descriptors
1371 CritScope cr(&crit_);
1372 for (size_t i = 0; i < dispatchers_.size(); ++i) {
1373 Dispatcher *pdispatcher = dispatchers_[i];
1374 int fd = pdispatcher->GetDescriptor();
1375 uint32 ff = 0;
1376 int errcode = 0;
1377
1378 // Reap any error code, which can be signaled through reads or writes.
1379 // TODO: Should we set errcode if getsockopt fails?
1380 if (FD_ISSET(fd, &fdsRead) || FD_ISSET(fd, &fdsWrite)) {
1381 socklen_t len = sizeof(errcode);
1382 ::getsockopt(fd, SOL_SOCKET, SO_ERROR, &errcode, &len);
1383 }
1384
1385 // Check readable descriptors. If we're waiting on an accept, signal
1386 // that. Otherwise we're waiting for data, check to see if we're
1387 // readable or really closed.
1388 // TODO: Only peek at TCP descriptors.
1389 if (FD_ISSET(fd, &fdsRead)) {
1390 FD_CLR(fd, &fdsRead);
1391 if (pdispatcher->GetRequestedEvents() & DE_ACCEPT) {
1392 ff |= DE_ACCEPT;
1393 } else if (errcode || pdispatcher->IsDescriptorClosed()) {
1394 ff |= DE_CLOSE;
1395 } else {
1396 ff |= DE_READ;
1397 }
1398 }
1399
1400 // Check writable descriptors. If we're waiting on a connect, detect
1401 // success versus failure by the reaped error code.
1402 if (FD_ISSET(fd, &fdsWrite)) {
1403 FD_CLR(fd, &fdsWrite);
1404 if (pdispatcher->GetRequestedEvents() & DE_CONNECT) {
1405 if (!errcode) {
1406 ff |= DE_CONNECT;
1407 } else {
1408 ff |= DE_CLOSE;
1409 }
1410 } else {
1411 ff |= DE_WRITE;
1412 }
1413 }
1414
1415 // Tell the descriptor about the event.
1416 if (ff != 0) {
1417 pdispatcher->OnPreEvent(ff);
1418 pdispatcher->OnEvent(ff, errcode);
1419 }
1420 }
1421 }
1422
1423 // Recalc the time remaining to wait. Doing it here means it doesn't get
1424 // calced twice the first time through the loop
1425 if (ptvWait) {
1426 ptvWait->tv_sec = 0;
1427 ptvWait->tv_usec = 0;
1428 struct timeval tvT;
1429 gettimeofday(&tvT, NULL);
1430 if ((tvStop.tv_sec > tvT.tv_sec)
1431 || ((tvStop.tv_sec == tvT.tv_sec)
1432 && (tvStop.tv_usec > tvT.tv_usec))) {
1433 ptvWait->tv_sec = tvStop.tv_sec - tvT.tv_sec;
1434 ptvWait->tv_usec = tvStop.tv_usec - tvT.tv_usec;
1435 if (ptvWait->tv_usec < 0) {
1436 ASSERT(ptvWait->tv_sec > 0);
1437 ptvWait->tv_usec += 1000000;
1438 ptvWait->tv_sec -= 1;
1439 }
1440 }
1441 }
1442 }
1443
1444 return true;
1445}
1446
1447static void GlobalSignalHandler(int signum) {
1448 PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
1449}
1450
1451bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
1452 void (*handler)(int)) {
1453 // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
1454 // otherwise set one.
1455 if (handler == SIG_IGN || handler == SIG_DFL) {
1456 if (!InstallSignal(signum, handler)) {
1457 return false;
1458 }
1459 if (signal_dispatcher_) {
1460 signal_dispatcher_->ClearHandler(signum);
1461 if (!signal_dispatcher_->HasHandlers()) {
1462 signal_dispatcher_.reset();
1463 }
1464 }
1465 } else {
1466 if (!signal_dispatcher_) {
1467 signal_dispatcher_.reset(new PosixSignalDispatcher(this));
1468 }
1469 signal_dispatcher_->SetHandler(signum, handler);
1470 if (!InstallSignal(signum, &GlobalSignalHandler)) {
1471 return false;
1472 }
1473 }
1474 return true;
1475}
1476
1477Dispatcher* PhysicalSocketServer::signal_dispatcher() {
1478 return signal_dispatcher_.get();
1479}
1480
1481bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
1482 struct sigaction act;
1483 // It doesn't really matter what we set this mask to.
1484 if (sigemptyset(&act.sa_mask) != 0) {
1485 LOG_ERR(LS_ERROR) << "Couldn't set mask";
1486 return false;
1487 }
1488 act.sa_handler = handler;
1489#if !defined(__native_client__)
1490 // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
1491 // and it's a nuisance. Though some syscalls still return EINTR and there's no
1492 // real standard for which ones. :(
1493 act.sa_flags = SA_RESTART;
1494#else
1495 act.sa_flags = 0;
1496#endif
1497 if (sigaction(signum, &act, NULL) != 0) {
1498 LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
1499 return false;
1500 }
1501 return true;
1502}
1503#endif // WEBRTC_POSIX
1504
1505#if defined(WEBRTC_WIN)
1506bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
1507 int cmsTotal = cmsWait;
1508 int cmsElapsed = 0;
1509 uint32 msStart = Time();
1510
1511 fWait_ = true;
1512 while (fWait_) {
1513 std::vector<WSAEVENT> events;
1514 std::vector<Dispatcher *> event_owners;
1515
1516 events.push_back(socket_ev_);
1517
1518 {
1519 CritScope cr(&crit_);
1520 size_t i = 0;
1521 iterators_.push_back(&i);
1522 // Don't track dispatchers_.size(), because we want to pick up any new
1523 // dispatchers that were added while processing the loop.
1524 while (i < dispatchers_.size()) {
1525 Dispatcher* disp = dispatchers_[i++];
1526 if (!process_io && (disp != signal_wakeup_))
1527 continue;
1528 SOCKET s = disp->GetSocket();
1529 if (disp->CheckSignalClose()) {
1530 // We just signalled close, don't poll this socket
1531 } else if (s != INVALID_SOCKET) {
1532 WSAEventSelect(s,
1533 events[0],
1534 FlagsToEvents(disp->GetRequestedEvents()));
1535 } else {
1536 events.push_back(disp->GetWSAEvent());
1537 event_owners.push_back(disp);
1538 }
1539 }
1540 ASSERT(iterators_.back() == &i);
1541 iterators_.pop_back();
1542 }
1543
1544 // Which is shorter, the delay wait or the asked wait?
1545
1546 int cmsNext;
1547 if (cmsWait == kForever) {
1548 cmsNext = cmsWait;
1549 } else {
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00001550 cmsNext = std::max(0, cmsTotal - cmsElapsed);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001551 }
1552
1553 // Wait for one of the events to signal
1554 DWORD dw = WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()),
1555 &events[0],
1556 false,
1557 cmsNext,
1558 false);
1559
1560 if (dw == WSA_WAIT_FAILED) {
1561 // Failed?
1562 // TODO: need a better strategy than this!
1563 WSAGetLastError();
1564 ASSERT(false);
1565 return false;
1566 } else if (dw == WSA_WAIT_TIMEOUT) {
1567 // Timeout?
1568 return true;
1569 } else {
1570 // Figure out which one it is and call it
1571 CritScope cr(&crit_);
1572 int index = dw - WSA_WAIT_EVENT_0;
1573 if (index > 0) {
1574 --index; // The first event is the socket event
1575 event_owners[index]->OnPreEvent(0);
1576 event_owners[index]->OnEvent(0, 0);
1577 } else if (process_io) {
1578 size_t i = 0, end = dispatchers_.size();
1579 iterators_.push_back(&i);
1580 iterators_.push_back(&end); // Don't iterate over new dispatchers.
1581 while (i < end) {
1582 Dispatcher* disp = dispatchers_[i++];
1583 SOCKET s = disp->GetSocket();
1584 if (s == INVALID_SOCKET)
1585 continue;
1586
1587 WSANETWORKEVENTS wsaEvents;
1588 int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
1589 if (err == 0) {
1590
1591#if LOGGING
1592 {
1593 if ((wsaEvents.lNetworkEvents & FD_READ) &&
1594 wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
1595 LOG(WARNING) << "PhysicalSocketServer got FD_READ_BIT error "
1596 << wsaEvents.iErrorCode[FD_READ_BIT];
1597 }
1598 if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
1599 wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
1600 LOG(WARNING) << "PhysicalSocketServer got FD_WRITE_BIT error "
1601 << wsaEvents.iErrorCode[FD_WRITE_BIT];
1602 }
1603 if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
1604 wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
1605 LOG(WARNING) << "PhysicalSocketServer got FD_CONNECT_BIT error "
1606 << wsaEvents.iErrorCode[FD_CONNECT_BIT];
1607 }
1608 if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
1609 wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
1610 LOG(WARNING) << "PhysicalSocketServer got FD_ACCEPT_BIT error "
1611 << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
1612 }
1613 if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
1614 wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
1615 LOG(WARNING) << "PhysicalSocketServer got FD_CLOSE_BIT error "
1616 << wsaEvents.iErrorCode[FD_CLOSE_BIT];
1617 }
1618 }
1619#endif
1620 uint32 ff = 0;
1621 int errcode = 0;
1622 if (wsaEvents.lNetworkEvents & FD_READ)
1623 ff |= DE_READ;
1624 if (wsaEvents.lNetworkEvents & FD_WRITE)
1625 ff |= DE_WRITE;
1626 if (wsaEvents.lNetworkEvents & FD_CONNECT) {
1627 if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
1628 ff |= DE_CONNECT;
1629 } else {
1630 ff |= DE_CLOSE;
1631 errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
1632 }
1633 }
1634 if (wsaEvents.lNetworkEvents & FD_ACCEPT)
1635 ff |= DE_ACCEPT;
1636 if (wsaEvents.lNetworkEvents & FD_CLOSE) {
1637 ff |= DE_CLOSE;
1638 errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
1639 }
1640 if (ff != 0) {
1641 disp->OnPreEvent(ff);
1642 disp->OnEvent(ff, errcode);
1643 }
1644 }
1645 }
1646 ASSERT(iterators_.back() == &end);
1647 iterators_.pop_back();
1648 ASSERT(iterators_.back() == &i);
1649 iterators_.pop_back();
1650 }
1651
1652 // Reset the network event until new activity occurs
1653 WSAResetEvent(socket_ev_);
1654 }
1655
1656 // Break?
1657 if (!fWait_)
1658 break;
1659 cmsElapsed = TimeSince(msStart);
1660 if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
1661 break;
1662 }
1663 }
1664
1665 // Done
1666 return true;
1667}
1668#endif // WEBRTC_WIN
1669
1670} // namespace rtc