3 * Copyright 2004--2005, Google Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
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.
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.
28 #include "talk/base/win32socketserver.h"
29 #include "talk/base/byteorder.h"
30 #include "talk/base/common.h"
31 #include "talk/base/logging.h"
32 #include "talk/base/winping.h"
33 #include "talk/base/win32window.h"
34 #include <ws2tcpip.h> // NOLINT
38 ///////////////////////////////////////////////////////////////////////////////
40 ///////////////////////////////////////////////////////////////////////////////
42 // TODO: Move this to a common place where PhysicalSocketServer can
45 static const uint16 PACKET_MAXIMUMS[] = {
46 65535, // Theoretical maximum, Hyperchannel
48 17914, // 16Mb IBM Token Ring
50 // 4464 // IEEE 802.5 (4Mb max)
52 // 2048, // Wideband Network
53 2002, // IEEE 802.5 (4Mb recommended)
54 // 1536, // Expermental Ethernet Networks
55 // 1500, // Ethernet, Point-to-Point (default)
57 1006, // SLIP, ARPANET
58 // 576, // X.25 Networks
59 // 544, // DEC IP Portal
61 508, // IEEE 802/Source-Rt Bridge, ARCNET
62 296, // Point-to-Point (low delay)
63 68, // Official minimum
64 0, // End of list marker
67 static const int IP_HEADER_SIZE = 20u;
68 static const int ICMP_HEADER_SIZE = 8u;
69 static const int ICMP_PING_TIMEOUT_MILLIS = 10000u;
71 // TODO: Enable for production builds also? Use FormatMessage?
73 LPCSTR WSAErrorToString(int error, LPCSTR *description_result) {
74 LPCSTR string = "Unspecified";
75 LPCSTR description = "Unspecified description";
79 description = "Operation succeeded";
82 string = "WSAEWOULDBLOCK";
83 description = "Using a non-blocking socket, will notify later";
87 description = "Access denied, or sharing violation";
89 case WSAEADDRNOTAVAIL:
90 string = "WSAEADDRNOTAVAIL";
91 description = "Address is not valid in this context";
94 string = "WSAENETDOWN";
95 description = "Network is down";
98 string = "WSAENETUNREACH";
99 description = "Network is up, but unreachable";
102 string = "WSANETRESET";
103 description = "Connection has been reset due to keep-alive activity";
105 case WSAECONNABORTED:
106 string = "WSAECONNABORTED";
107 description = "Aborted by host";
110 string = "WSAECONNRESET";
111 description = "Connection reset by host";
114 string = "WSAETIMEDOUT";
115 description = "Timed out, host failed to respond";
117 case WSAECONNREFUSED:
118 string = "WSAECONNREFUSED";
119 description = "Host actively refused connection";
122 string = "WSAEHOSTDOWN";
123 description = "Host is down";
125 case WSAEHOSTUNREACH:
126 string = "WSAEHOSTUNREACH";
127 description = "Host is unreachable";
129 case WSAHOST_NOT_FOUND:
130 string = "WSAHOST_NOT_FOUND";
131 description = "No such host is known";
134 if (description_result) {
135 *description_result = description;
140 void ReportWSAError(LPCSTR context, int error, const SocketAddress& address) {
141 LPCSTR description_string;
142 LPCSTR error_string = WSAErrorToString(error, &description_string);
143 LOG(LS_INFO) << context << " = " << error
144 << " (" << error_string << ":" << description_string << ") ["
145 << address.ToString() << "]";
148 void ReportWSAError(LPCSTR context, int error, const SocketAddress& address) {}
151 /////////////////////////////////////////////////////////////////////////////
152 // Win32Socket::EventSink
153 /////////////////////////////////////////////////////////////////////////////
155 #define WM_SOCKETNOTIFY (WM_USER + 50)
156 #define WM_DNSNOTIFY (WM_USER + 51)
158 struct Win32Socket::DnsLookup {
161 char buffer[MAXGETHOSTSTRUCT];
164 class Win32Socket::EventSink : public Win32Window {
166 explicit EventSink(Win32Socket * parent) : parent_(parent) { }
170 virtual bool OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam,
172 virtual void OnNcDestroy();
175 bool OnSocketNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result);
176 bool OnDnsNotify(WPARAM wParam, LPARAM lParam, LRESULT& result);
178 Win32Socket * parent_;
181 void Win32Socket::EventSink::Dispose() {
183 if (::IsWindow(handle())) {
184 ::DestroyWindow(handle());
190 bool Win32Socket::EventSink::OnMessage(UINT uMsg, WPARAM wParam,
191 LPARAM lParam, LRESULT& result) {
193 case WM_SOCKETNOTIFY:
195 return OnSocketNotify(uMsg, wParam, lParam, result);
197 return OnDnsNotify(wParam, lParam, result);
202 bool Win32Socket::EventSink::OnSocketNotify(UINT uMsg, WPARAM wParam,
203 LPARAM lParam, LRESULT& result) {
206 int wsa_event = WSAGETSELECTEVENT(lParam);
207 int wsa_error = WSAGETSELECTERROR(lParam);
209 // Treat connect timeouts as close notifications
210 if (uMsg == WM_TIMER) {
211 wsa_event = FD_CLOSE;
212 wsa_error = WSAETIMEDOUT;
216 parent_->OnSocketNotify(static_cast<SOCKET>(wParam), wsa_event, wsa_error);
220 bool Win32Socket::EventSink::OnDnsNotify(WPARAM wParam, LPARAM lParam,
224 int error = WSAGETASYNCERROR(lParam);
226 parent_->OnDnsNotify(reinterpret_cast<HANDLE>(wParam), error);
230 void Win32Socket::EventSink::OnNcDestroy() {
232 LOG(LS_ERROR) << "EventSink hwnd is being destroyed, but the event sink"
233 " hasn't yet been disposed.";
239 /////////////////////////////////////////////////////////////////////////////
241 /////////////////////////////////////////////////////////////////////////////
243 Win32Socket::Win32Socket()
244 : socket_(INVALID_SOCKET), error_(0), state_(CS_CLOSED), connect_time_(0),
245 closing_(false), close_error_(0), sink_(NULL), dns_(NULL) {
248 Win32Socket::~Win32Socket() {
252 bool Win32Socket::CreateT(int family, int type) {
254 int proto = (SOCK_DGRAM == type) ? IPPROTO_UDP : IPPROTO_TCP;
255 socket_ = ::WSASocket(family, type, proto, NULL, NULL, 0);
256 if (socket_ == INVALID_SOCKET) {
260 if ((SOCK_DGRAM == type) && !SetAsync(FD_READ | FD_WRITE)) {
266 int Win32Socket::Attach(SOCKET s) {
267 ASSERT(socket_ == INVALID_SOCKET);
268 if (socket_ != INVALID_SOCKET)
271 ASSERT(s != INVALID_SOCKET);
272 if (s == INVALID_SOCKET)
276 state_ = CS_CONNECTED;
278 if (!SetAsync(FD_READ | FD_WRITE | FD_CLOSE))
284 void Win32Socket::SetTimeout(int ms) {
286 ::SetTimer(sink_->handle(), 1, ms, 0);
289 SocketAddress Win32Socket::GetLocalAddress() const {
290 sockaddr_storage addr = {0};
291 socklen_t addrlen = sizeof(addr);
292 int result = ::getsockname(socket_, reinterpret_cast<sockaddr*>(&addr),
294 SocketAddress address;
296 SocketAddressFromSockAddrStorage(addr, &address);
298 LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
304 SocketAddress Win32Socket::GetRemoteAddress() const {
305 sockaddr_storage addr = {0};
306 socklen_t addrlen = sizeof(addr);
307 int result = ::getpeername(socket_, reinterpret_cast<sockaddr*>(&addr),
309 SocketAddress address;
311 SocketAddressFromSockAddrStorage(addr, &address);
313 LOG(LS_WARNING) << "GetRemoteAddress: unable to get remote addr, socket="
319 int Win32Socket::Bind(const SocketAddress& addr) {
320 ASSERT(socket_ != INVALID_SOCKET);
321 if (socket_ == INVALID_SOCKET)
324 sockaddr_storage saddr;
325 size_t len = addr.ToSockAddrStorage(&saddr);
326 int err = ::bind(socket_,
327 reinterpret_cast<sockaddr*>(&saddr),
328 static_cast<int>(len));
333 int Win32Socket::Connect(const SocketAddress& addr) {
334 if (state_ != CS_CLOSED) {
339 if (!addr.IsUnresolvedIP()) {
340 return DoConnect(addr);
343 LOG_F(LS_INFO) << "async dns lookup (" << addr.hostname() << ")";
344 DnsLookup * dns = new DnsLookup;
346 // Explicitly create the sink ourselves here; we can't rely on SetAsync
347 // because we don't have a socket_ yet.
350 // TODO: Replace with IPv6 compatible lookup.
351 dns->handle = WSAAsyncGetHostByName(sink_->handle(), WM_DNSNOTIFY,
352 addr.hostname().c_str(), dns->buffer,
353 sizeof(dns->buffer));
356 LOG_F(LS_ERROR) << "WSAAsyncGetHostByName error: " << WSAGetLastError();
363 dns->port = addr.port();
365 state_ = CS_CONNECTING;
369 int Win32Socket::DoConnect(const SocketAddress& addr) {
370 if ((socket_ == INVALID_SOCKET) && !CreateT(addr.family(), SOCK_STREAM)) {
373 if (!SetAsync(FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE)) {
377 sockaddr_storage saddr = {0};
378 size_t len = addr.ToSockAddrStorage(&saddr);
379 connect_time_ = Time();
380 int result = connect(socket_,
381 reinterpret_cast<SOCKADDR*>(&saddr),
382 static_cast<int>(len));
383 if (result != SOCKET_ERROR) {
384 state_ = CS_CONNECTED;
386 int code = WSAGetLastError();
387 if (code == WSAEWOULDBLOCK) {
388 state_ = CS_CONNECTING;
390 ReportWSAError("WSAAsync:connect", code, addr);
401 int Win32Socket::GetError() const {
405 void Win32Socket::SetError(int error) {
409 Socket::ConnState Win32Socket::GetState() const {
413 int Win32Socket::GetOption(Option opt, int* value) {
416 if (TranslateOption(opt, &slevel, &sopt) == -1)
419 char* p = reinterpret_cast<char*>(value);
420 int optlen = sizeof(value);
421 return ::getsockopt(socket_, slevel, sopt, p, &optlen);
424 int Win32Socket::SetOption(Option opt, int value) {
427 if (TranslateOption(opt, &slevel, &sopt) == -1)
430 const char* p = reinterpret_cast<const char*>(&value);
431 return ::setsockopt(socket_, slevel, sopt, p, sizeof(value));
434 int Win32Socket::Send(const void* buffer, size_t length) {
435 int sent = ::send(socket_,
436 reinterpret_cast<const char*>(buffer),
437 static_cast<int>(length),
443 int Win32Socket::SendTo(const void* buffer, size_t length,
444 const SocketAddress& addr) {
445 sockaddr_storage saddr;
446 size_t addr_len = addr.ToSockAddrStorage(&saddr);
447 int sent = ::sendto(socket_, reinterpret_cast<const char*>(buffer),
448 static_cast<int>(length), 0,
449 reinterpret_cast<sockaddr*>(&saddr),
450 static_cast<int>(addr_len));
455 int Win32Socket::Recv(void* buffer, size_t length) {
456 int received = ::recv(socket_, static_cast<char*>(buffer),
457 static_cast<int>(length), 0);
459 if (closing_ && received <= static_cast<int>(length))
464 int Win32Socket::RecvFrom(void* buffer, size_t length,
465 SocketAddress* out_addr) {
466 sockaddr_storage saddr;
467 socklen_t addr_len = sizeof(saddr);
468 int received = ::recvfrom(socket_, static_cast<char*>(buffer),
469 static_cast<int>(length), 0,
470 reinterpret_cast<sockaddr*>(&saddr), &addr_len);
472 if (received != SOCKET_ERROR)
473 SocketAddressFromSockAddrStorage(saddr, out_addr);
474 if (closing_ && received <= static_cast<int>(length))
479 int Win32Socket::Listen(int backlog) {
480 int err = ::listen(socket_, backlog);
481 if (!SetAsync(FD_ACCEPT))
486 state_ = CS_CONNECTING;
490 Win32Socket* Win32Socket::Accept(SocketAddress* out_addr) {
491 sockaddr_storage saddr;
492 socklen_t addr_len = sizeof(saddr);
493 SOCKET s = ::accept(socket_, reinterpret_cast<sockaddr*>(&saddr), &addr_len);
495 if (s == INVALID_SOCKET)
498 SocketAddressFromSockAddrStorage(saddr, out_addr);
499 Win32Socket* socket = new Win32Socket;
500 if (0 == socket->Attach(s))
506 int Win32Socket::Close() {
508 if (socket_ != INVALID_SOCKET) {
509 err = ::closesocket(socket_);
510 socket_ = INVALID_SOCKET;
516 WSACancelAsyncRequest(dns_->handle);
529 int Win32Socket::EstimateMTU(uint16* mtu) {
530 SocketAddress addr = GetRemoteAddress();
537 if (!ping.IsValid()) {
538 error_ = EINVAL; // can't think of a better error ID
542 for (int level = 0; PACKET_MAXIMUMS[level + 1] > 0; ++level) {
543 int32 size = PACKET_MAXIMUMS[level] - IP_HEADER_SIZE - ICMP_HEADER_SIZE;
544 WinPing::PingResult result = ping.Ping(addr.ipaddr(), size,
545 ICMP_PING_TIMEOUT_MILLIS, 1, false);
546 if (result == WinPing::PING_FAIL) {
547 error_ = EINVAL; // can't think of a better error ID
550 if (result != WinPing::PING_TOO_LARGE) {
551 *mtu = PACKET_MAXIMUMS[level];
560 void Win32Socket::CreateSink() {
561 ASSERT(NULL == sink_);
564 sink_ = new EventSink(this);
565 sink_->Create(NULL, L"EventSink", 0, 0, 0, 0, 10, 10);
568 bool Win32Socket::SetAsync(int events) {
571 ASSERT(NULL != sink_);
574 // start the async select
575 if (WSAAsyncSelect(socket_, sink_->handle(), WM_SOCKETNOTIFY, events)
585 bool Win32Socket::HandleClosed(int close_error) {
586 // WM_CLOSE will be received before all data has been read, so we need to
587 // hold on to it until the read buffer has been drained.
590 close_error_ = close_error;
591 return (::recv(socket_, &ch, 1, MSG_PEEK) <= 0);
594 void Win32Socket::PostClosed() {
595 // If we see that the buffer is indeed drained, then send the close.
597 ::PostMessage(sink_->handle(), WM_SOCKETNOTIFY,
598 socket_, WSAMAKESELECTREPLY(FD_CLOSE, close_error_));
601 void Win32Socket::UpdateLastError() {
602 error_ = WSAGetLastError();
605 int Win32Socket::TranslateOption(Option opt, int* slevel, int* sopt) {
607 case OPT_DONTFRAGMENT:
608 *slevel = IPPROTO_IP;
609 *sopt = IP_DONTFRAGMENT;
612 *slevel = SOL_SOCKET;
616 *slevel = SOL_SOCKET;
620 *slevel = IPPROTO_TCP;
624 LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
633 void Win32Socket::OnSocketNotify(SOCKET socket, int event, int error) {
634 // Ignore events if we're already closed.
635 if (socket != socket_)
641 if (error != ERROR_SUCCESS) {
642 ReportWSAError("WSAAsync:connect notify", error, addr_);
644 int32 duration = TimeSince(connect_time_);
645 LOG(LS_INFO) << "WSAAsync:connect error (" << duration
646 << " ms), faking close";
649 // If you get an error connecting, close doesn't really do anything
650 // and it certainly doesn't send back any close notification, but
651 // we really only maintain a few states, so it is easiest to get
652 // back into a known state by pretending that a close happened, even
653 // though the connect event never did occur.
654 SignalCloseEvent(this, error);
657 int32 duration = TimeSince(connect_time_);
658 LOG(LS_INFO) << "WSAAsync:connect (" << duration << " ms)";
660 state_ = CS_CONNECTED;
661 SignalConnectEvent(this);
667 if (error != ERROR_SUCCESS) {
668 ReportWSAError("WSAAsync:read notify", error, addr_);
670 SignalReadEvent(this);
675 if (error != ERROR_SUCCESS) {
676 ReportWSAError("WSAAsync:write notify", error, addr_);
678 SignalWriteEvent(this);
683 if (HandleClosed(error)) {
684 ReportWSAError("WSAAsync:close notify", error, addr_);
686 SignalCloseEvent(this, error);
692 void Win32Socket::OnDnsNotify(HANDLE task, int error) {
693 if (!dns_ || dns_->handle != task)
698 hostent* pHost = reinterpret_cast<hostent*>(dns_->buffer);
699 uint32 net_ip = *reinterpret_cast<uint32*>(pHost->h_addr_list[0]);
700 ip = NetworkToHost32(net_ip);
703 LOG_F(LS_INFO) << "(" << IPAddress(ip).ToSensitiveString()
704 << ", " << error << ")";
707 SocketAddress address(ip, dns_->port);
708 error = DoConnect(address);
715 SignalCloseEvent(this, error_);
722 ///////////////////////////////////////////////////////////////////////////////
724 // Provides cricket base services on top of a win32 gui thread
725 ///////////////////////////////////////////////////////////////////////////////
727 static UINT s_wm_wakeup_id = 0;
728 const TCHAR Win32SocketServer::kWindowName[] = L"libjingle Message Window";
730 Win32SocketServer::Win32SocketServer(MessageQueue* message_queue)
731 : message_queue_(message_queue),
735 if (s_wm_wakeup_id == 0)
736 s_wm_wakeup_id = RegisterWindowMessage(L"WM_WAKEUP");
737 if (!wnd_.Create(NULL, kWindowName, 0, 0, 0, 0, 0, 0)) {
738 LOG_GLE(LS_ERROR) << "Failed to create message window.";
742 Win32SocketServer::~Win32SocketServer() {
743 if (wnd_.handle() != NULL) {
744 KillTimer(wnd_.handle(), 1);
749 Socket* Win32SocketServer::CreateSocket(int type) {
750 return CreateSocket(AF_INET, type);
753 Socket* Win32SocketServer::CreateSocket(int family, int type) {
754 return CreateAsyncSocket(family, type);
757 AsyncSocket* Win32SocketServer::CreateAsyncSocket(int type) {
758 return CreateAsyncSocket(AF_INET, type);
761 AsyncSocket* Win32SocketServer::CreateAsyncSocket(int family, int type) {
762 Win32Socket* socket = new Win32Socket;
763 if (socket->CreateT(family, type)) {
770 void Win32SocketServer::SetMessageQueue(MessageQueue* queue) {
771 message_queue_ = queue;
774 bool Win32SocketServer::Wait(int cms, bool process_io) {
777 // Spin the Win32 message pump at least once, and as long as requested.
778 // This is the Thread::ProcessMessages case.
779 uint32 start = Time();
782 SetTimer(wnd_.handle(), 0, cms, NULL);
783 // Get the next available message. If we have a modeless dialog, give
784 // give the message to IsDialogMessage, which will return true if it
785 // was a message for the dialog that it handled internally.
786 // Otherwise, dispatch as usual via Translate/DispatchMessage.
787 b = GetMessage(&msg, NULL, 0, 0);
789 LOG_GLE(LS_ERROR) << "GetMessage failed.";
792 if (!hdlg_ || !IsDialogMessage(hdlg_, &msg)) {
793 TranslateMessage(&msg);
794 DispatchMessage(&msg);
797 KillTimer(wnd_.handle(), 0);
798 } while (b && TimeSince(start) < cms);
799 } else if (cms != 0) {
800 // Sit and wait forever for a WakeUp. This is the Thread::Send case.
803 b = GetMessage(&msg, NULL, s_wm_wakeup_id, s_wm_wakeup_id);
805 CritScope scope(&cs_);
809 // No-op (cms == 0 && !process_io). This is the Pump case.
815 void Win32SocketServer::WakeUp() {
817 // Set the "message pending" flag, if not already set.
819 CritScope scope(&cs_);
825 PostMessage(wnd_.handle(), s_wm_wakeup_id, 0, 0);
829 void Win32SocketServer::Pump() {
830 // Clear the "message pending" flag.
832 CritScope scope(&cs_);
836 // Dispatch all the messages that are currently in our queue. If new messages
837 // are posted during the dispatch, they will be handled in the next Pump.
838 // We use max(1, ...) to make sure we try to dispatch at least once, since
839 // this allow us to process "sent" messages, not included in the size() count.
841 for (size_t max_messages_to_process = _max<size_t>(1, message_queue_->size());
842 max_messages_to_process > 0 && message_queue_->Get(&msg, 0, false);
843 --max_messages_to_process) {
844 message_queue_->Dispatch(&msg);
847 // Anything remaining?
848 int delay = message_queue_->GetDelay();
850 KillTimer(wnd_.handle(), 1);
852 SetTimer(wnd_.handle(), 1, delay, NULL);
856 bool Win32SocketServer::MessageWindow::OnMessage(UINT wm, WPARAM wp,
857 LPARAM lp, LRESULT& lr) {
858 bool handled = false;
859 if (wm == s_wm_wakeup_id || (wm == WM_TIMER && wp == 1)) {
867 } // namespace talk_base