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